Wednesday, December 26, 2007

Adding the single quotes into sql server statements...

Hi,

Yesterday one of my junior came to me and ask a simple question :

How to add the single quotes into sql server statements ?????

lets say I want to update an existing record. The sql for it is below:
update sampletable set field='data' where id='#'
ok, very simple . Now what if the data includes a single quote in it? Something like “vishal’s store”.

the resulting sql query looks like this:
update tblLocation set Loc_Name='Vishal's Store' where id='Vishal25648'
this will generate errors in the sql statement, because after the single quote is encountered the sql parser looks for a where clause.

Any ideas of how to get around this? And special character codes in sql for single quote?

Although this is a simple issue but many of novices are still unaware and tried the backslashes and all to get it done.

But the answer is as simple as the question J

The answer is this:
update tblLocation set Loc_Name='Vishal''s Store' where id='Vishal25648'
All you need is to add 1 (one) extra single quote before the intended single quote. Sounds simple isn’t it.
Note: this answer is specific to sql server 2000. The syntax might be different for oracle, sybase, or others.