How do I escape a single quote in SQL Server?

前端 未结 13 1907
情话喂你
情话喂你 2020-11-21 07:01

I\'m trying to insert some text data into a table in SQL Server 9.

The text includes a single quote(\').

How do I escape that?

相关标签:
13条回答
  • 2020-11-21 07:31

    Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.

    PRINT 'It''s me, Arul.';
    

    we are going to look on some other alternate ways of escaping the single quotes.

    1.UNICODE Characters

    39 is the UNICODE character of Single Quote. So we can use it like below.

    PRINT 'Hi,it'+CHAR(39)+'s Arul.';
    PRINT 'Helo,it'+NCHAR(39)+'s Arul.';
    

    2.QUOTED_IDENTIFIER

    Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.

    SET QUOTED_IDENTIFIER OFF;
    PRINT "It's Arul."
    SET QUOTED_IDENTIFIER ON;
    

    CONCLUSION

    The above mentioned methods are applicable to both AZURE and On Premises .

    0 讨论(0)
  • 2020-11-21 07:37

    If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after your query.

    For example

    SET QUOTED_IDENTIFIER OFF;
    
    UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");
    
    SET QUOTED_IDENTIFIER ON;
    -- set OFF then ON again
    
    0 讨论(0)
  • 2020-11-21 07:37

    This should work

    DECLARE @singleQuote CHAR 
    SET @singleQuote =  CHAR(39)
    
    insert into my_table values('hi, my name'+ @singleQuote +'s tim.')
    
    0 讨论(0)
  • 2020-11-21 07:40

    Double quotes option helped me

    SET QUOTED_IDENTIFIER OFF;
    insert into my_table values("hi, my name's tim.");
    SET QUOTED_IDENTIFIER ON;
    
    0 讨论(0)
  • 2020-11-21 07:42

    The following syntax will escape you ONLY ONE quotation mark:

    SELECT ''''
    

    The result will be a single quote. Might be very helpful for creating dynamic SQL :).

    0 讨论(0)
  • 2020-11-21 07:44

    How about:

    insert into my_table values('hi, my name' + char(39) + 's tim.')
    
    0 讨论(0)
提交回复
热议问题