How do I escape a single quote in SQL Server?

前端 未结 13 1851
情话喂你
情话喂你 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:20

    2 ways to work around this:


    for ' you can simply double it in the string, e.g. select 'I''m happpy' -- will get: I'm happy


    For any charactor you are not sure of: in sql server you can get any char's unicode by select unicode(':') (you keep the number)

    So this case you can also select 'I'+nchar(39)+'m happpy'

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

    Just insert a ' before anything to be inserted. It will be like a escape character in sqlServer

    Example: When you have a field as, I'm fine. you can do: UPDATE my_table SET row ='I''m fine.';

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

    I had the same problem, but mine was not based of static data in the SQL code itself, but from values in the data.

    This code lists all the columns names and data types in my database:

    SELECT DISTINCT QUOTENAME(COLUMN_NAME),DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
    

    But some column names actually have a single-quote embedded in the name of the column!, such as ...

    [MyTable].[LEOS'DATACOLUMN]
    

    To process these, I had to use the REPLACE function along with the suggested QUOTED_IDENTIFIER setting. Otherwise it would be a syntax error, when the column is used in a dynamic SQL.

    SET QUOTED_IDENTIFIER OFF;
        SET @sql = 'SELECT DISTINCT ''' + @TableName + ''',''' + REPLACE(@ColumnName,"'","''") + ...etc
    SET QUOTED_IDENTIFIER ON;
    
    0 讨论(0)
  • 2020-11-21 07:24

    Single quotes are escaped by doubling them up, just as you've shown us in your example. The following SQL illustrates this functionality. I tested it on SQL Server 2008:

    DECLARE @my_table TABLE (
        [value] VARCHAR(200)
    )
    
    INSERT INTO @my_table VALUES ('hi, my name''s tim.')
    
    SELECT * FROM @my_table
    

    Results

    value
    ==================
    hi, my name's tim.
    
    0 讨论(0)
  • 2020-11-21 07:24

    The doubling up of the quote should have worked, so it's peculiar that it didn't work for you; however, an alternative is using double quote characters, instead of single ones, around the string. I.e.,

    insert into my_table values("hi, my name's tim.");

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

    This should work: use a back slash and put a double quote

    "UPDATE my_table SET row =\"hi, my name's tim.\";
    
    0 讨论(0)
提交回复
热议问题