I want to use quotation with escape character. How can I do?
I have received error in SQL Server
Unclosed quotation mark after the character string.
I am writing sql query in a varchar variable but I have received that error:
Unclosed quotation mark after the character string.
I want to use quotation mark as escape char.
Thanks in advance
Escaping quotes in MSSQL is done by a double quote, so a
''
or a""
will produce one escaped'
and"
, respectively.You can escape quotation like this:
result will be
You need to just replace
'
with''
inside your stringYou can also use
REPLACE(@name, '''', '''''')
if generating the SQL dynamicallyIf you want to escape inside a like statement then you need to use the ESCAPE syntax
It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F
If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).
e.g. instead of doing
try this:
You can define your escape character, but you can only use it with a
LIKE
clause.Example:
Here it will search for
%
in whole string and this is how one can useESCAPE
identifier inSQL Server
.