问题
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