How can I remove leading and trailing quotes in SQL Server?

前端 未结 14 1402
青春惊慌失措
青春惊慌失措 2020-12-15 03:28

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 remo

相关标签:
14条回答
  • 2020-12-15 03:54

    To remove both quotes you could do this

    SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
    

    you can either assign or project the resulting value

    0 讨论(0)
  • 2020-12-15 03:56

    Some UDFs for re-usability.

    Left Trimming by character (any number)

    CREATE FUNCTION [dbo].[LTRIMCHAR] (@Input NVARCHAR(max), @TrimChar CHAR(1) = ',')
    RETURNS NVARCHAR(max)
    AS
    BEGIN
          RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(@Input,' ','¦'), @TrimChar, ' ')), ' ', @TrimChar),'¦',' ')
    END
    

    Right Trimming by character (any number)

    CREATE FUNCTION [dbo].[RTRIMCHAR] (@Input NVARCHAR(max), @TrimChar CHAR(1) = ',')
    RETURNS NVARCHAR(max)
    AS
    BEGIN
         RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(@Input,' ','¦'), @TrimChar, ' ')), ' ', @TrimChar),'¦',' ')
    END
    

    Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).

    0 讨论(0)
  • 2020-12-15 03:57

    I have just tested this code in MS SQL 2008 and validated it.

    Remove left-most quote:

    UPDATE MyTable
    SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
    WHERE LEFT(FieldName, 1) = '"'
    

    Remove right-most quote: (Revised to avoid error from implicit type conversion to int)

    UPDATE MyTable
    SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
    WHERE RIGHT(FieldName, 1) = '"'
    
    0 讨论(0)
  • 2020-12-15 04:02

    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
    
    0 讨论(0)
  • 2020-12-15 04:04

    You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test

    0 讨论(0)
  • 2020-12-15 04:05

    I use this:

    UPDATE DataImport
    SET PRIO = 
            CASE WHEN LEN(PRIO) < 2 
            THEN 
                (CASE PRIO WHEN '""' THEN '' ELSE PRIO END) 
            ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"', 
                SUBSTRING(PRIO, 2, LEN(PRIO) - 2)) 
            END
    
    0 讨论(0)
提交回复
热议问题