Escape Character in SQL Server

2019-01-08 13:27发布

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

5条回答
啃猪蹄的小仙女
2楼-- · 2019-01-08 13:43

Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.

查看更多
不美不萌又怎样
3楼-- · 2019-01-08 13:49

You can escape quotation like this:

select 'it''s escaped'

result will be

it's escaped
查看更多
虎瘦雄心在
4楼-- · 2019-01-08 13:56

You need to just replace ' with '' inside your string

SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'

You can also use REPLACE(@name, '''', '''''') if generating the SQL dynamically

If 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

查看更多
欢心
5楼-- · 2019-01-08 13:57

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'
查看更多
趁早两清
6楼-- · 2019-01-08 14:06

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.

查看更多
登录 后发表回答