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?
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;