SQL Server 中的转义字符

Escape Character in SQL Server(SQL Server 中的转义字符)
本文介绍了SQL Server 中的转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用带转义字符的引号.我该怎么办?

I want to use quotation with escape character. How can I do?

我在 SQL Server 中收到错误

I have received error in SQL Server

字符串后的非右引号.

我正在 varchar 变量中编写 SQL 查询,但我收到了该错误:

I'm writing SQL query in a varchar variable but I have received that error:

字符串后的非右引号.

我想使用引号作为转义字符.

I want to use quotation mark as an escape char.

推荐答案

要转义 ' 你只需要在前面加上一个:''

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'

结果是

it's escaped

如果您要将 SQL 连接到 VARCHAR 中执行(即动态 SQL),那么我建议您对 SQL 进行参数化.这样做的好处是有助于防止 SQL 注入,另外意味着您不必担心像这样转义引号(您可以通过加倍引号来实现).

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).

例如而不是做

DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(@SQL)

试试这个:

DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'

这篇关于SQL Server 中的转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)