Jr. A developer asked me the other day how to escape single quote? I find this question very interesting.
User can escape single quote using two single quotes (NOT double quote).
Following T-SQL Script will give error
USE AdventureWorks
GO
SELECT *
FROM Person.Address
WHERE City = ‘Villeneuve-d’Ascq’
GO
Resultset:
Error: 105 Unclosed quotation mark after the character string ‘
To fix the error mentioned above, escape single quotes with two single quotes as displayed in following example.
USE AdventureWorks GO SELECT * FROM Person.Address WHERE City = 'Villeneuve-d''Ascq' GO
Well, it is a pretty easy way to escape single quotes. Here are a few interesting quotes about single and double quotes. In fiction, at least with American English (AmE), there’s really no use for single quotation marks other than as a quote within another quote. In general, quotation marks are used to mark direct speech in a text, to indicate irony, or to highlight the title of works that are part of a larger whole — like chapters of a novel, an article in a magazine or newspaper.
Let me know what you think of this blog post by leaving your opinion in the comment sections.
Reference: Pinal Dave (https://blog.sqlauthority.com)
74 Comments. Leave new
Edited for some typo
@tableName varchar(100),
@Code nvarchar(10),
@label nvarchar(max),
@Lang nchar(2),
@Reg nchar(2),
@Fran nchar(3)
SET @query = ‘INSERT INTO ‘ + @tableName
+ ‘ (Code,label,Lang,Reg,Fran) VALUES’
+’ (”’+ @Code +”’,”’ @label +”’,”’+@Lang+”’,”’+@Reg+”’,”’+@Fran+”’)’
execute(@query)
this query will not work when i have label like this
A00 ”B & Y – “NIPO””
how to fix this
@sqlquestions
Did you try escaping all those quotes?
Just go with brian advice, you can either replace or remove quotes and it will work. If any one have any thing better please put comment.
–remove single quote
set @label = REPLACE(@label ,””,”)
–replace single quote with doule quote
set @label = REPLACE(@label, ””, ‘”‘);
Thanks
Thanks to God, the one and only, that I found this post. Thank you very much for this post.
I need to get the error resolved for the code below
————–error————————–
USE AVME
Declare @SQL nvarchar(MAX)
Declare @docpath nvarchar(MAX)
Set @docpath = N’E:\Workflow\SPP\Attachments\ModelCodes\claim.xls’
Set @SQL = ‘INSERT INTO [Tactical.Claim_LineItems_BULK_Audi] ([JObCreator], [ModelCode],
[ChassisNo], [CommissionNo], [AGSupport],[AVMESupport], [Brand], [Remark])
SELECT *
FROM OPENROWSET (”Microsoft.ACE.OLEDB.12.0”, ”Excel 12.0;;Database=”’+@docpath+”’,
”select * from [Sheet1$]”)’
PRINT @SQL
EXEC(@SQL)
————error———————————————-
INSERT INTO [Tactical.Claim_LineItems_BULK_Audi] ([JObCreator], [ModelCode],
[ChassisNo], [CommissionNo], [AGSupport],[AVMESupport], [Brand], [Remark])
SELECT *
FROM OPENROWSET (‘Microsoft.ACE.OLEDB.12.0’, ‘Excel 12.0;;Database=’E:\Workflow\SPP\Attachments\ModelCodes\claim.xls’,
‘select * from [Sheet1$]’)
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ‘E’.
Msg 105, Level 15, State 1, Line 5
Unclosed quotation mark after the character string ‘)’.
Dont use single quote around file name
Hi,
I have a new variation on this problem. I have a varchar() field called Notes where users can enter anything they want. If they use a single quote for a grammatical contraction, then it causes an error when I try to pass the string in an UPDATE statement. So, for intance:
New account, didn’t ask for conversion.
causes an “Unclosed quotation mark after the character string” error.
I noticed that when I BULK imported the table into SQLServer, it wrapped all these text strings in double quotes:
“New account, didn’t ask for conversion.”
but that doesn’t seem to fix the problem. When I try to pass that text string in an UPDATE statement I still get the error.
Is there a way to wrap up these text strings so they automatically get escaped by SQLServer? I understand the syntax for escaping them when I’m writing the whole SQL statement, but I can’t ask my users to avoid single quotes in their comments.
Thanks,
Bill J.
You need to double the single quotes
Hi Bill,
I had similar problem like yours. Just repeating code from above
Just add the following to your T-SQL
Declare @find nvarchar(5)
Declare @replace nvarchar(5)
Declare @notes –this is the variable used in your update statement
Set @find = ”+ char(39) +” — these are two single quotes
Set @replace = ”+char(39)+char(39)+”
Set @notes = replace(@notes,@find,@replace) –this will replace one single quote with two double quote.
This will be helpful in statement such as Update tbl_name set = ‘%+@notes+%’
where
I hope this helps.
Cheers, bhattji
Also refer
Hi Pinal,
My question is whether sql server 2008 has taken care of apostrophe problem. I am not facing any problem of apostrophe in my code when i insert data in table from UI. I am using SQL server 2008 and stored procedure to insert data from UI to database. I tried to find but not able to find any blog where it is mentioned so still in doubt how SP is adding data with apostrophe in table. I want to make myself double sure.
This does not always work…Here is an example:
drop table dirresults
CREATE TABLE DirResults (Diroutput VARCHAR(500))
INSERT DirResults
exec master..xp_cmdshell ‘osql -S127.0.0.1,1450 -T -Q “exec sp_executesql N”select * from pubs..authors where state = ”a”””‘
Hi Gurus,
I hope here I am going to get my answer.
The code is working from SQL Server 2000 to 2008.
However the application is crash in 2008R2.
Here is the code:
CREATE TABLE abc (
col1 varchar (7000) NOT NULL,
PRIMARY KEY (col1))
INSERT INTO abc ( col1 )
VALUES( ‘a’ ) // Different Values in a loop
Check the SQLDB CODE If It is Duplicate Then
Do Some Calculation
ELSE
Loop
In 2008R2 as soon as it finds a duplicate it crashed.
Thanks for really good post.Best regards.
I am using a fully loaded sqlite3 database where embedded single and double quotes are included in many of the varchar fields. What select query could i write to simply query the database without things breaking?
for example
where col2 is know to contain embedded single and double quotes
Select col1, col2 from table_Name;
ALTER PROCEDURE [dbo].[DBSP_SF_GetAccountsLikeAccNo]
@AccountNo VARCHAR(20),
@BusinessName VARCHAR(40),
@Type VARCHAR(2)
AS
BEGIN
DECLARE @str VARCHAR(100)
SELECT @str=REPLACE(@BusinessName,””,”)
IF @Type = ‘AN’
BEGIN
SELECT AccountNo, BusinessName FROM CustomerDetails WITH (NOLOCK) WHERE AccountNo like @AccountNo + ‘%’
END
ELSE IF @Type = ‘BN’
BEGIN
SELECT AccountNo, BusinessName FROM CustomerDetails WITH (NOLOCK) WHERE BusinessName like @str + ‘%’
END
END
if the value is Andersons The Grocery Store .in this I did not get any problem. But, ‘Anderson’s “The Grocery Store”‘ I am getting error like Unclosed quotation mark after the character string ‘). Can you please help out me by giving proper code (how to replace two single quotes in place of one single quote).
plz helpme any modify my SP
Thank you so much Nikhil Bhatt
thanks! Big fan of your posts
Hi Pinal,
I am developing a .net application and as part of this, i have a stored procedure that gets me the data with required format. This stored procedure has dynamic sql in it where the formatting of the data takes place.
Below is the query that i am using to format any data based on its column datatype. This query just does the following, I have used master DB for this example,
1. @query variable is formed with a sql query where this query has a case statement in which column name is passed to scalar function(udfSelDataTypeOfColumn) and datatype is got from it.
2. If this datatype is of CHAR or NCHAR or NVARCHAR or VARCHAR then i want the output of the column value enclosed in a single quote.
Suppose, the output value is a varchar with value as Pinal then this query has to return ‘Pinal’ else for other datatypes same value can be returned like (int)1234, (bit)1
I tried formatting with single quotes and concatinating but no luck.
Please let me know a solution to this problem and explain me how single quotes intepretation is done by sql runtime.
USE master
DECLARE @query NVARCHAR(MAX),
@charDataType NVARCHAR(20)
SELECT @charDataType=”’%char%”’
select @query=’SELECT TOP 10
CASE WHEN dbo.udfSelDataTypeOfColumn(”name”) like ‘+@charDataType+ ‘then ”” +name+ ”” else ”name” end
FROM spt_values WITH(NOLOCK)’
EXEC sp_executesql @query
I have getting same problem in SQL string kindly help me out about this error my sring is
“INSERT INTO LoginMaster(UserName, Password, DistrictID, AgencyID, Address, BlockID, PanchayatID, UserType, ContactNo, EmailAddress, SQuestion, SAnswer, Status) VALUES (‘” + UserName.Text + “‘, ‘” & Password.Text & “‘,'” & district.SelectedValue & “‘,'” & agency.SelectedValue & “‘,'” & AgencyAddress.Text & “‘,’0′,’0’,'” & UserType.SelectedValue & “‘,'” & contactno.Text & “‘,'” & emailaddress.Text & “‘ ,'” & SQuestion.Text & “‘,'” & SAnswer.Text & “‘,’1’)”
plz help me
Thanks.
Excellent Blog
I am creating a SP the exports DB responses to Excel file, excel file code is working fine, I am using Dynamic SQL, when i am appending SP parameter variable inside the dynamic query i am facing issues of ‘ (quotes) i think .The SP parameter is stored in @ForYear variable. when i am hard coding the @ForYear with say 2012 the query is executing without error. please help.
–WHEN I EXECUTE THE SP
exec Proc_ExportEntireYearlyResponsesToExcel 2012
–THE ERROR IS
Unclosed quotation mark after the character string ‘)SELECT * FROM @PVTable’.
ALTER PROCEDURE [dbo].[Proc_ExportEntireYearlyResponsesToExcel]
— Add the parameters for the stored procedure here
@ForYear Varchar(250)
AS
BEGIN
EXEC sp_configure ‘show advanced options’, 1; RECONFIGURE
EXEC sp_configure ‘Ad Hoc Distributed Queries’, 1; RECONFIGURE
Declare @Var1 as nvarchar(MAX)
set @Var1=””+ ‘Microsoft.ACE.OLEDB.12.0′ +”” +’,’
Declare @Var2 as nvarchar(MAX)
set @Var2=””+’Excel 12.0;Database=C:destinationEntireYearlyMESRespondentResponses.xlsx;’+”” +’,’
Declare @Var3 as nvarchar(MAX)
set @Var3=””+’SELECT * FROM [Sheet2$]’+””
declare @Var4 as nvarchar(max)
set @Var4=@Var1+@Var2+@Var3
PRINT ‘OLEDB for Office 2007 –> ‘+@Var4 — Correctly printed [OLEDB for Office 2007 –> ‘Microsoft.ACE.OLEDB.12.0′,’Excel 12.0;Database=C:destinationEntireYearlyMESRespondentResponses.xlsx;’,’SELECT * FROM [Sheet2$]’]
Declare @ResponsesQuery varchar(MAX)
set @ResponsesQuery=
(‘
declare @QCol table
(
ColumnId int identity(1,1),
QuestionIdentifierID int
)
insert into
@QCol (QuestionIdentifierID)
select
QuestionIdentifierID
from
dbo.QuestionIdentifier as qi with(nolock) left join
dbo.Question as q with(nolock) on qi.QuestionID = q.QuestionID
where
q.SurveyID = 1
declare @PVTable table
(
RespondentID int,
IndustryName varchar(250),
BusinessSectorName varchar(250),
CompanyName varchar(250),
OpenDateTime varchar(250),
[1] varchar(250),
[2] varchar(250),
[3] varchar(250),
[4] varchar(250),
[5] varchar(250),
[6] varchar(250)
)
insert into @PVTable
select
RespondentID,
IndustryName,
BusinessSectorName,
CompanyName,
CONVERT(CHAR(4),OpenDateTime,120) as OpenDateTime,
[1] as Q18_1,
[2] as Q18_2,
[3] as Q18_3,
[4] as Q12_1,
[5] as Q12_2,
[6] as Q36_1
from
(
select
qt1.RespondentID,
qt1.IndustryName,
qt1.BusinessSectorName,
qt1.CompanyName,
qt1.OpenDateTime
from
@QCol as qc join
(
select distinct
rt.RespondentID,
i.[Name] as IndustryName,
bs.[Name] as BusinessSectorName,
cmp.[Name] as CompanyName,
sc.OpenDateTime,
from
dbo.Table1 rt left join
dbo.Table2 r on rt.RespondentID = r.RespondentID left join
.
.
.
.
where
c.ChoiceListID is null and
CONVERT(CHAR(4), sc.OpenDateTime, 120)=’+@ForYear+’
) qt1 on qc.QuestionIdentifierID = qt1.QuestionIdentifierId
union
select
qt2.RespondentID,
qt2.IndustryName,
qt2.BusinessSectorName,
qt2.CompanyName,
qt2.OpenDateTime,
from
@QCol as qc join
(
select distinct
t1.RespondentID,
t1.IndustryName,
t1.BusinessSectorName,
t1.CompanyName,
t1.OpenDateTime,
from
dbo.Choice c join
(
select
rt.RespondentID,
i.[Name] as IndustryName,
bs.[Name] as BusinessSectorName,
cmp.[Name] as CompanyName,
sc.OpenDateTime,
from
dbo.Table1 rt left join
dbo.Table2 r on rt.RespondentID = r.RespondentID left join
.
.
.
.
where
CONVERT(CHAR(4), sc.OpenDateTime, 120)=’+@ForYear+’
) t1 on c.ChoiceListID = t1.ChoiceListID and t1.AnswerValue = cast(c.[Value] as varchar)
) qt2 on qc.QuestionIdentifierID = qt2.QuestionIdentifierID
) t2
pivot
(
max([AnswerValue])
for QuestionIdentifierID in
([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52],[53],[54],[55],[56],[57],[58],[59],[60],[61],[62],[63],[64],[65],[66],[67],[68],[69],[70],[71],[72],[73],[74],[75],[76],[77],[78],[79],[80],[81],[82],[83],[84],[85],[86],[87],[88],[89],[90],[91],[92],[93],[94],[95],[96],[97],[98],[99],[100],[101],[102],[103],[104],[105])
) as pvt
order by RespondentID;
INSERT INTO OPENROWSET (‘+@Var4+’) SELECT * FROM @PVTable
‘)
–FILE MANUPLATION CODE HERE and it works fine
EXEC Master.dbo.xp_fileexist @FileToBeDeletedOnExistance, @File_Exists OUT
IF @File_Exists = 1
begin
execute (@ResponsesQuery) — error is here
END
ELSE
begin
— any other query
END
–WHEN I EXECUTE THE SP
exec Proc_ExportEntireYearlyResponsesToExcel 2012
–THE ERROR IS
Unclosed quotation mark after the character string ‘)SELECT * FROM @PVTable’.
Hello Friends, I am using a SP to export yearly Responses to an excel file by providing year to an SP, the @ForYear variable captures the parameter. Excel file code and other stuff is working fine when i am hard coding the @ForYear as 2012 in the dynamic SQL. I am using dynamic SQL and inserting the SQL parameter (@ForYear) inside it and then executing the Dynamic SQL based of file exist logic
–WHEN I EXECUTE THE SP
exec Proc_ExportEntireYearlyResponsesToExcel 2012
–THE ERROR IS
Unclosed quotation mark after the character string ‘)SELECT * FROM @PVTable’.
AGAIN WHEN I HARDCODE THE @ForYear as 2012 or 2011 data is coming in the excel file and there is no error
PLEASE HELP ITS AN EOD TASK
–Query starts here
ALTER PROCEDURE [dbo].[Proc_ExportEntireYearlyResponsesToExcel]
— Add the parameters for the stored procedure here
@ForYear Varchar(250)
AS
BEGIN
EXEC sp_configure ‘show advanced options’, 1; RECONFIGURE
EXEC sp_configure ‘Ad Hoc Distributed Queries’, 1; RECONFIGURE
Declare @Var1 as nvarchar(MAX)
set @Var1=””+ ‘Microsoft.ACE.OLEDB.12.0′ +”” +’,’
Declare @Var2 as nvarchar(MAX)
set @Var2=””+’Excel 12.0;Database=C:destinationEntireYearlyMESRespondentResponses.xlsx;’+”” +’,’
Declare @Var3 as nvarchar(MAX)
set @Var3=””+’SELECT * FROM [Sheet2$]’+””
declare @Var4 as nvarchar(max)
set @Var4=@Var1+@Var2+@Var3
PRINT ‘OLEDB for Office 2007 –> ‘+@Var4 — Correctly printed [OLEDB for Office 2007 –> ‘Microsoft.ACE.OLEDB.12.0′,’Excel 12.0;Database=C:destinationEntireYearlyMESRespondentResponses.xlsx;’,’SELECT * FROM [Sheet2$]’]
Declare @ResponsesQuery varchar(MAX)
set @ResponsesQuery=
(‘
declare @QCol table
(
ColumnId int identity(1,1),
QuestionIdentifierID int
)
insert into
@QCol (QuestionIdentifierID)
select
QuestionIdentifierID
from
dbo.QuestionIdentifier as qi with(nolock) left join
dbo.Question as q with(nolock) on qi.QuestionID = q.QuestionID
where
q.SurveyID = 1
declare @PVTable table
(
RespondentID int,
IndustryName varchar(250),
BusinessSectorName varchar(250),
CompanyName varchar(250),
OpenDateTime varchar(250),
[1] varchar(250),
[2] varchar(250),
[3] varchar(250),
[4] varchar(250),
[5] varchar(250),
[6] varchar(250)
)
insert into @PVTable
select
RespondentID,
IndustryName,
BusinessSectorName,
CompanyName,
CONVERT(CHAR(4),OpenDateTime,120) as OpenDateTime,
[1] as Q18_1,
[2] as Q18_2,
[3] as Q18_3,
[4] as Q12_1,
[5] as Q12_2,
[6] as Q36_1
from
(
select
qt1.RespondentID,
qt1.IndustryName,
qt1.BusinessSectorName,
qt1.CompanyName,
qt1.OpenDateTime
from
@QCol as qc join
(
select distinct
rt.RespondentID,
i.[Name] as IndustryName,
bs.[Name] as BusinessSectorName,
cmp.[Name] as CompanyName,
sc.OpenDateTime,
from
dbo.Table1 rt left join
dbo.Table2 r on rt.RespondentID = r.RespondentID left join
.
.
.
.
where
c.ChoiceListID is null and
CONVERT(CHAR(4), sc.OpenDateTime, 120)=’+@ForYear+’
) qt1 on qc.QuestionIdentifierID = qt1.QuestionIdentifierId
union
select
qt2.RespondentID,
qt2.IndustryName,
qt2.BusinessSectorName,
qt2.CompanyName,
qt2.OpenDateTime,
from
@QCol as qc join
(
select distinct
t1.RespondentID,
t1.IndustryName,
t1.BusinessSectorName,
t1.CompanyName,
t1.OpenDateTime,
from
dbo.Choice c join
(
select
rt.RespondentID,
i.[Name] as IndustryName,
bs.[Name] as BusinessSectorName,
cmp.[Name] as CompanyName,
sc.OpenDateTime,
from
dbo.Table1 rt left join
dbo.Table2 r on rt.RespondentID = r.RespondentID left join
.
.
.
.
where
CONVERT(CHAR(4), sc.OpenDateTime, 120)=’+@ForYear+’
) t1 on c.ChoiceListID = t1.ChoiceListID and t1.AnswerValue = cast(c.[Value] as varchar)
) qt2 on qc.QuestionIdentifierID = qt2.QuestionIdentifierID
) t2
pivot
(
max([AnswerValue])
for QuestionIdentifierID in
([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52],[53],[54],[55],[56],[57],[58],[59],[60],[61],[62],[63],[64],[65],[66],[67],[68],[69],[70],[71],[72],[73],[74],[75],[76],[77],[78],[79],[80],[81],[82],[83],[84],[85],[86],[87],[88],[89],[90],[91],[92],[93],[94],[95],[96],[97],[98],[99],[100],[101],[102],[103],[104],[105])
) as pvt
order by RespondentID;
INSERT INTO OPENROWSET (‘+@Var4+’)SELECT * FROM @PVTable
‘)
–FILE MANUPLATION CODE HERE and it works fine
EXEC Master.dbo.xp_fileexist @FileToBeDeletedOnExistance, @File_Exists OUT
IF @File_Exists = 1
begin
execute (@ResponsesQuery) — error is here
END
ELSE
begin
— any other query
END
–Query ends here
–WHEN I EXECUTE THE SP
exec Proc_ExportEntireYearlyResponsesToExcel 2012
–THE ERROR IS
Unclosed quotation mark after the character string ‘)SELECT * FROM @PVTable’.
Hi pinal dev
i have a question like this…..
i have a string say s=’kumar’ and i want to insert ‘UMAR’ only into my data base pls give me a query.
Kumar, What is the final objective
Are you trying to remove the first letter of string and present the rest
OR
Are you trying to get the last four letters from the string.
Please elaborate.
bhattji
I have a table fields which contains characters like ‘s and because of SQL limitation I am getting errors in application. Such characters sequence stored because of laps during conversion time. Can any one help me to replace escape ‘ characters with other one…
Thanks…
Devang