如何在事务 sql 语句中使用单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6835529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use single quotations inside a transact sql statement
提问by hamed aj
i want use single quotations inside a transact sql statement, then execute that statement.
我想在事务 sql 语句中使用单引号,然后执行该语句。
for example my query is:
例如我的查询是:
Select * FROM MyTable WHERE MyTable.Id = '1'
now i want use like this:
现在我想这样使用:
Declare @SQLQuery AS NVarchar(4000)
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = '1' '
Execute (@SQLQuery)
this not work, and this error occurred :
这不起作用,并且发生了此错误:
Invalid column name '1'
无效的列名“1”
I know problem is quotations in left and right side of the 1
我知道问题是在 1 的左侧和右侧引用
this is a sample and i want use of this way to a large query
这是一个示例,我想使用这种方式进行大型查询
of course, i want use local variable instead for example '1' and my local variable is varchar
当然,我想使用局部变量代替例如“1”,而我的局部变量是 varchar
any idea?
任何的想法?
回答by Ryan
Just escape the quotes:
只需转义引号:
change
改变
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = '1' '
to
到
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ''1'' '
** Edit **
** 编辑 **
To include a local variable in the result, you could updated your query like this:
要在结果中包含局部变量,您可以像这样更新查询:
DECLARE @SQLQuery varchar(200)
DECLARE @tmpInt int
SET @tmpInt = 2
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ' +
convert(varchar, @tmpInt) + ' '
回答by Narnian
Use double ticks to escape them:
使用双勾来逃避它们:
Declare @SQLQuery AS NVarchar(4000)
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ''1'' '
Execute (@SQLQuery)
If you want to use a local variable as you mention in your comment, you can do this:
如果你想使用你在评论中提到的局部变量,你可以这样做:
Declare @SQLQuery AS NVarchar(4000)
Declare @Id AS NVarchar(3)
SET @Id = '1'
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id= ''' + @Id + ''''
Execute (@SQLQuery)
回答by Mat
Double the single quotes in the quote!
将引号中的单引号加倍!
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ''1'' '
回答by webLacky3rdClass
wrap the one single quote in to more like '''
and the tics will work as well.
将一个单引号'''
括起来更像,抽动也会起作用。
回答by Beth
Try using double-quotes instead:
尝试使用双引号代替:
SET @SQLQuery = "Select * FROM MyTable WHERE MyTable.Id = '" + @Id + "'"