문제

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, ''))
도움이 되었습니까?

해결책

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

다른 팁

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

TRIM() function requires SQL Server 2017.

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.

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

select case when (@str like '"%"') then substring(@str,2,len(@str)-2) else @str end as string
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 dba.stackexchange
scroll top