1378

I am 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.');

3
  • 51
    "it threw me some errors" -- What were these errors?
    – llamaoo7
    Oct 19, 2009 at 1:24
  • 2
    Yes because the right way to insert single quotes in MSSQL is to double them. The example you show us should be working. How to you make this SQL query, with which language ? Or is it in SQL Server Management Studio ?
    – MaxiWheat
    Oct 19, 2009 at 1:32
  • 1
    Possible duplicate of Replace single quotes in SQL Server. Jan 25, 2016 at 14:52

15 Answers 15

1953

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.
4
  • 26
    i was looking at the wrong place to fix my problem. it was not a character escape issue after all. my issue was that the data length was over the limit. thanks for reassuring me that using the single quote twice is the right way of escaping the character.
    – tim_wonil
    Oct 19, 2009 at 1:41
  • So, if I have a text containing 10k words it'll be necessary I replace all my text? Feb 14, 2014 at 22:26
  • 3
    @ViniciusLima: The short answer is yes. That would change of course depending on the technology you're going to use to store the data. If you're using an ORM it will do it for you. If you're building your SQL commands manually you'll want to use the language's "prepared statements" functionality. If you're doing it in Management Studio then you'll have to do the replace.
    – Cᴏʀʏ
    Feb 15, 2014 at 16:44
  • 1
    i.e. two single quotes for one. [''] => ['] Apr 28, 2014 at 12:32
92

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
4
  • 3
    Normally I use the doubled up approach, but where I was generating dynamic SQL which was then ran across multiple servers and databases, this solution worked for me whereas the doubling didn't in one specific case. Thanks for this! Jul 2, 2015 at 12:12
  • Be careful when referencing views and indexes on computed columns or you may get an error. stackoverflow.com/questions/9235527/…
    – datagod
    Mar 9, 2017 at 15:52
  • @RichardMoss, +1. same scenario with you. doubled up approach is the initial solution. For complex queries like dynamic SQL across multiple servers, this will work, doubled up approach may not Dec 20, 2017 at 14:17
  • 4
    It's worth noting for the uninitiated that SET QUOTED_IDENTIFIER alters the behavior of the double-quote and not the behavior of the apostrophe. In particular, setting its value to OFF means that a double quote can be used for delimiting strings. With it turned ON (the default) it is used for delimiting identifiers, like column names, so that they can contain spaces or SQL keywords.
    – donperk
    Mar 22, 2022 at 21:36
74

How about:

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

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 .

25

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'

19

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

1
  • 7
    What if the text contains both single and double quotes? Also, aren't double quotes reserved for field names only? Nov 28, 2017 at 11:07
6

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.

1
  • 3
    Note that single quote is char(39), not char(27). 27 is the hex code for single quote. 39 is the decimal code for it.
    – Rory
    May 26, 2021 at 19:44
5

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

5

Double quotes option helped me

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

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

Example:

When you have a field as, I'm fine.

you can do:

UPDATE my_table SET row ='I''m fine.';
1
  • Isn’t that exactly what the OP did, and the same as the top-voted answer already says? Presumably there must have been some other source of the error. Jun 24, 2019 at 22:00
0

This should work

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

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

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

Just Add N before value

insert into my_table values(N'hi, my name's tim.');
1
  • Adding the N in front doesn't work as the SQL engine will throw an error saying Unclosed quotation mark after the character string. You will still need to double escape the value. The N tells sql to use NVARCHAR. Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
    – KeyOfJ
    Apr 16 at 20:53
-3

The STRING_ESCAPE funtion can be used on newer versions of SQL Server

2
  • 6
    According to the documentation: "Currently STRING_ESCAPE can only escape JSON special characters"
    – norgie
    May 5, 2021 at 7:25
  • And it cannot be used for escape the '
    – raiserle
    Sep 16, 2021 at 11:00
-4

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

"UPDATE my_table SET row =\"hi, my name's tim.\";
1
  • What do you mean? You are saying that PRINT \"hi, my name's tim.\"; is going to work in SSMS? It doesn't work at all and nobody has ever told that it works. Dec 19, 2019 at 10:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.