tags:

views:

961

answers:

3

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.

For example:

"this is a test message"

should become

this is a test message

I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.

A: 

you could replace the quotes with an empty string...

SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
       LeadingAndTrailingRemoved = CASE 
           WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
           ELSE MyTest
           END  
FROM   MyTable
Scott Ivey
there may be quotes within the string and I don't want to remove these - just the leading and trailing quotes.
adeel825
updated example to a case statement to remove just leading and trailing when both are present.
Scott Ivey
+3  A: 

Not tested by it should give some direction:

Update MyTable Set [FieldName]=SUBSTR([FieldName], 2, LEN([FieldName]) WHERE LEFT([FieldName],1) = '"'

And

Update MyTable Set [FieldName]=SUBSTR([FieldName], 1, LEN([FieldName]-1) WHERE RIGHT([FieldName],1) = '"'
WowtaH
This is correct, you can also use LEFT and RIGHT funcions.
tekBlues
G Mastros
SUBSTRING is the function in SQL Server. Not SUBSTR
Keltex
A: 

Hi

You can try this-

SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
  FROM TableName

cheers

Andriyev