Wednesday, December 24, 2008

SQL Insert with ' (quote)

First of all, the target audience of this article is not those who have spent some time already with SQL server but it's for those who are newbie to this field.
Lets start from the scratch by creating a simple table, named Shippers.
CREATE TABLE Shippers
(
ShipperID int IDENTITY(1,1),
CompanyName nvarchar(50) ,
Phone nvarchar(50)

)
If we write an insert to insert the data to the Shippers table like this:
Insert into Shippers(CompanyName, Phone) values ('ABC' ,'888-999-9999')

There won't be any problem but if we try to insert some data having quotation e.g. here after word Rock there is one quote and Muscle word is inside the quote mark will create problem
Insert into Shippers(CompanyName, Phone) values ('Rock's 'Muscle'' ,'XXX-999-9999')

The error will be like this
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 's'.
Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string ')
'.

Then we need to modify our query in the following way :
Insert into Shippers(CompanyName, Phone) values ('Rock''s ''Muscle''' ,'XXX-999-9999')
The simple funda is to put one additional quote for every exisiting single quote i.e. after word Rock instead of one there will be 2 quotes as shown in the above query and so on.

Happy querying and advanced Merry X-MAS :-)

No comments:

FEEDJIT Live Traffic Feed