Incorrect syntax near '=' sp_executesql

你说的曾经没有我的故事 提交于 2019-12-10 19:56:01

问题


I need to delete all rows in some table where value is empty string.(I have multiple table which got similar name).

I tryed to execute those sql statement which is in string:

DECLARE @sql AS NVARCHAR(MAX)
DECLARE @emptyValue AS NVARCHAR(1) =''    
set @sql = N'DELETE FROM SampleTable WHERE Value='+@emptyValue+''
exec sp_executesql @sql

But it's throw me error Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '='.

I tryed to figure it out about an hour now. Any help would be appreciated.

Edit: Here's what I get after deleting last quota. @tableName is nvarchar(MAX).


回答1:


Instead of doing string concatenation, parameterize the call to sp_executesql, for Sql Injection and other reasons (including caching of query plans, and not having to worry about escaping quotes :-):

DECLARE @sql AS NVARCHAR(MAX);
DECLARE @emptyValue AS NVARCHAR(1) ='';
set @sql = N'DELETE FROM SampleTable WHERE Value=@emptyValue';
exec sp_executesql @sql, N'@emptyValue NVARCHAR(1)', @emptyValue = @emptyValue;

Fiddle




回答2:


You have two quotes:

set @sql = N'DELETE FROM SampleTable WHERE Value='+@emptyValue+''

Change it to:

set @sql = N'DELETE FROM SampleTable WHERE Value='+@emptyValue

http://sqlfiddle.com/#!3/ce8e3/4




回答3:


If you can, I'd go with StuartLC's answer - parameters are clearly the way to go.

Just to show you what to do if you have no choice but to go this way, you can escape the single quotes. The quotes are necessary as the Value column appears to be a string (inferred from the default value set to @emptyValue in the question).

To escape a single quote, you need another single quote. Give this a try:

DECLARE @sql AS NVARCHAR(MAX)
DECLARE @emptyValue AS NVARCHAR(1) = ''
set @sql = N'DELETE FROM SampleTable WHERE Value='''+@emptyValue+''''
exec sp_executesql @sql

Note you could always PRINT @sql to see the script, rather than blindly trying to run it.



来源:https://stackoverflow.com/questions/22066376/incorrect-syntax-near-sp-executesql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!