How do I escape a single quote in SQL Server

A single quote can be escaped by doubling them up in MSSQL server. There are many ways to escape a single quote in SQL server. Let us look at the below examples to find out more information.

Sample SQL Query to escape a single quote

DECLARE @my_table TABLE (
    [value] VARCHAR(200)
)

INSERT INTO @my_table VALUES ('hi, my name''s srinivas.')

SELECT * FROM @my_table

-- Output
--hi, my name's srinivas.

The other alternate way would be to use the built-in method char(39) which also result in single quotes. Hence, while inserting the data into the table append the char(39) which MSSQL will decode and append the quotes into the data.

DECLARE @my_table TABLE (
    [value] VARCHAR(200)
)

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

SELECT * FROM @my_table

-- Output
--hi, my name's srinivas.

Even for the update statement and select statement same logic can be applied to escape the single quotes.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like