Understanding Single quotes

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 '''','''''''','''''''''''','''''''''''''''',''''''''''''''''''''')

Published 19 February 2008 12:49 by Madhivanan

Comments

# SQL SERVER - How to Escape Single Quotes - Fix: Error: 105 Unclosed quotation mark after the character string ‘ « Journey to SQL Authority with Pinal Dave

PingBack from http://blog.sqlauthority.com/2008/02/17/sql-server-how-to-escape-single-quotes-fix-error-105-unclosed-quotation-mark-after-the-character-string/

# re: Understanding Single quotes

25 February 2008 12:33 by Jayasimha M N

nice article thank u Madhivanan

# Server Side Guy » Escaping Single Quotes in MS SQL Server (T-SQL)

Pingback from  Server Side Guy  » Escaping Single Quotes in MS SQL Server (T-SQL)