2

I have a field that may start and end with quotes. I only want to remove the quotes if the string starts and ends with quotes. If quotes exists inside the string then I wish to retain them.

I have used REVERSE and stuff which works if the field does start and end with quotes but if it does not it just returns null.

How can I ensure I still get the field result if it did not start with quotes?

What I have:

REVERSE(STUFF(REVERSE(STUFF(fieldname, CHARINDEX('"', fieldname), LEN('"'), '')), CHARINDEX('"', REVERSE(STUFF(fieldname, CHARINDEX('"', fieldname), LEN('"'), '')), 1), 1, ''))
2
  • I only want to remove the quotes if the string starts and ends with quotes. If quotes exists inside the string then I wish to retain them. – Round Aug 7 '19 at 12:08
  • What if a value only starts or only ends with a double quote? – Aaron Bertrand Aug 7 '19 at 12:12
6

You could try something like this

SELECT CASE WHEN RIGHT(fieldname,1) = '"' AND LEFT(fieldname,1) = '"' THEN REVERSE(STUFF(REVERSE(STUFF(fieldname, 1, 1, '')), 1, 1, '')) 
       WHEN RIGHT(fieldname,1) = '"' THEN REVERSE(STUFF(REVERSE(fieldname), 1, 1, '')) 
       WHEN LEFT(fieldname,1) = '"' THEN STUFF(fieldname, 1, 1, '')
       ELSE fieldname END as fieldname
FROM #temp;

DB<>Fiddle

0
5
SELECT TRIM(' "' FROM fieldname) fieldname
FROM tablename

TRIM() function requires SQL Server 2017.

0
4

Randi's answer works perfectly, and Akina's is much tidier if you are on SQL Server 2017 or better, but on older versions you can do this with slightly less code and fewer operations like reverse/stuff. Given this data:

CREATE TABLE #temp(col varchar(255));

INSERT #temp(col) 
  SELECT 'foo' UNION ALL SELECT '"bar"' 
  UNION ALL SELECT 'blat"' UNION ALL SELECT '"mort';

This query yields the same results:

SELECT col = SUBSTRING
(
  x,
  CASE s WHEN '"' THEN 2 ELSE 1 END,
  LEN(x) - CASE e WHEN '"' THEN 1 + CASE s WHEN '"' THEN 1 ELSE 0 END ELSE 0 END
)
FROM (SELECT x = col, s = LEFT(col,1), e = RIGHT(col,1) FROM #temp) y;

Results:

col
========
foo
bar
blat
mort

I'm assuming that a string only starting with a double quote or only ending with a double quote also needs that lone double quote removed.

1
-2
declare @str varchar(50)='"ajhd"lajhi"'

select case when (@str like '"%"') then substring(@str,2,len(@str)-2) else @str end as string
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.