How do I escape a single quote in SQL Server?

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

提交回复
热议问题