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 strin
You can escape quotation like this:
select 'it''s escaped'
result will be
it's escaped
You can define your escape character, but you can only use it with a LIKE
clause.
Example:
SELECT columns FROM table
WHERE column LIKE '%\%%' ESCAPE '\'
Here it will search for %
in whole string and this is how one can use ESCAPE
identifier in SQL Server
.
To escape '
you simly need to put another before: ''
As the second answer shows it's possible to escape single quote like this:
select 'it''s escaped'
result will be
it's escaped
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
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(@SQL)
try this:
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'
To keep the code easy to read, you can use square brackets []
to quote the string containing '
or vice versa .
Escaping quotes in MSSQL is done by a double quote, so a ''
or a ""
will produce one escaped '
and "
, respectively.
If you want to escape user input in a variable you can do like below within SQL
Set @userinput = replace(@userinput,'''','''''')
The @userinput will be now escaped with an extra single quote for every occurance of a quote