Understanding Single quotes within a SELECT statement

Published 19 February 08 12:19 PM | Madhivanan 

This is for newbies who struggle to understand how single quotes work in SQL Server

I have seen newbies worrying why the following doesnt work

SELECT columns from mytable where col ='Lifco's'

When you specify a value which has single quote, you need to double it

SELECT columns from mytable where col ='Lifco''s'

The following may be helpful (Run and see the result)

SELECT '','''','''''','''''''',''''''''''

When you use a static sql and express a value in a single quote then first and last sigle quotes specify that the value is a string. Then within those single quotes every double single quotes represent a single single quote

When you use a Dynamic sql then first and last sigle quotes specify that it is a dynamic sql. Then within those single quotes every double single quotes specify that it is a string.Then within those single quotes every four single quotes represent a single single quote

Run and see the result

EXEC('SELECT '''','''''''','''''''''''','''''''''''''''',''''''''''''''''''''')

Comments

# SQL Server Transact-SQL (SSQA.net) : Understanding Single quotes within a SELECT statement said on February 19, 2008 1:18 PM:

PingBack from http://sqlserver-qa.net/blogs/t-sql/archive/2008/02/19/3569.aspx

# Other SQL Server Blogs around the Web said on February 19, 2008 1:39 PM:

This is for newbies who struggle to understand how single quotes work in SQL Server I have seen newbies

# http://sqlserver-qa.net/blogs/t-sql/archive/2008/02/19/3569.aspx said on April 4, 2008 6:25 AM:

PingBack from http://frankthefrank.info/entry.php?id=kwws%3d22vtovhuyhu0td1qhw2eorjv2w0vto2dufklyh2533%3b23524%3c2689%3c1dvs%7b

Anonymous comments are disabled