[sql] How do I escape a single quote in SQL Server?

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 tried using two single quotes, but it threw me some errors.

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

This question is related to sql sql-server tsql delimiter single-quotes

The answer is


Also another thing to be careful of is whether or not it is really stored as a classic ASCII ' (ASCII 27) or Unicode 2019 (which looks similar, but not the same).

This isn't a big deal on inserts, but it can mean the world on selects and updates.
If it's the unicode value then escaping the ' in a WHERE clause (e.g where blah = 'Workers''s Comp') will return like the value you are searching for isn't there if the ' in "Worker's Comp" is actually the unicode value.

If your client application supports free-key, as well as copy and paste based input, it could be Unicode in some rows, and ASCII in others!

A simple way to confirm this is by doing some kind of open ended query that will bring back the value you are searching for, and then copy and paste that into notepad++ or some other unicode supporting editor.

The differing appearance between the ascii value and the unicode one should be obvious to the eyes, but if you lean towards the anal, it will show up as 27 (ascii) or 92 (unicode) in a hex editor.


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'


Double quotes option helped me

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

How about:

insert into my_table values('hi, my name' + char(39) + 's tim.')

This should work

DECLARE @singleQuote CHAR 
SET @singleQuote =  CHAR(39)

insert into my_table values('hi, my name'+ @singleQuote +'s tim.')

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.';


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

"UPDATE my_table SET row =\"hi, my name's tim.\";

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.");


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

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 :). enter image description here


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;

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.';

Doubling the Single Quotes Method

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.';

UNICODE Characters

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;

QUOTE_IDENTIFIER

CONCLUSION

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


Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to delimiter

How do I hide the PHP explode delimiter from submitted form results? How do I use a delimiter with Scanner.useDelimiter in Java? Split function in oracle to comma separated values with automatic sequence Split String by delimiter position using oracle SQL SQL split values to multiple rows How to use delimiter for csv in python Hive load CSV with commas in quoted fields How to escape indicator characters (i.e. : or - ) in YAML Delimiters in MySQL Split comma separated column data into additional columns

Examples related to single-quotes

Usage of the backtick character (`) in JavaScript How do I escape a single quote in SQL Server?