[sql-server-2008] How to handle-escape both single and double quotes in an SQL-Update statement

I have this sample T-SQL query and trying this on SQL-Server-2008.

DECLARE nvarchar(1000) @wstring = "I asked my son's teacher, "How is my son doing now?"" 

UPDATE tablename SET columnname = ' " & @wstring & " ' where ... blah ... blah

I know that the above query will throw error.

So how do I handle-escape both single and double quotes in an SQL-Update statement.

This question is related to sql-server-2008 sql-update

The answer is


When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.


In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation


I have solved a similar problem by first importing the text into an excel spreadsheet, then using the Substitute function to replace both the single and double quotes as required by SQL Server, eg. SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""")

In my case, I had many rows (each a line of data to be cleaned then inserted) and had the spreadsheet automatically generate insert queries for the text once the substitution had been done eg. ="INSERT INTO [dbo].[tablename] ([textcolumn]) VALUES ('" & SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""") & "')"

I hope that helps.


You can escape the quotes with a backslash:

"I asked my son's teacher, \"How is my son doing now?\""

Use "REPLACE" to remove special characters.

REPLACE(ColumnName ,' " ','')

Ex: -

--Query ---

DECLARE @STRING AS VARCHAR(100)
SET @STRING ='VI''RA""NJA "'

SELECT @STRING 
SELECT REPLACE(REPLACE(@STRING,'''',''),'"','') AS MY_NAME

--Result---

VI'RA""NJA"


Depending on what language you are programming in, you can use a function to replace double quotes with two double quotes.

For example in PHP that would be:

str_replace('"', '""', $string);

If you are trying to do that using SQL only, maybe REPLACE() is what you are looking for.

So your query would look something like this:

"UPDATE Table SET columnname = '" & REPLACE(@wstring, '"', '""') & "' where ... blah ... blah "

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"


Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to sql-update

Update some specific field of an entity in android Room How to perform update operations on columns of type JSONB in Postgres 9.4 MySQL - UPDATE multiple rows with different values in one query How to update multiple columns in single update statement in DB2 Update Multiple Rows in Entity Framework from a list of ids Update MySQL using HTML Form and PHP CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column? mysql after insert trigger which updates another table's column Update values from one column in same table to another in SQL Server I want to use CASE statement to update some records in sql server 2005