--sp_executesql version
--SET @SQLQUERY = 'UPDATE @TableName SET Brief = @Brief,
-- [Full] = @Full,
-- CreatedBy = @CreatedBy,
-- Department = @Department,
-- Answer = @Answer WHERE Id=@Id';
--SET @ParamDefinition=N'@TableName nvarchar(50),@Brief nvarchar(50),@Full nvarchar(MAX),@CreatedBy varchar(256),@Department varchar(256),@Answer nvarchar(MAX),@Id int'
-- exec sp_executesql @SQLQUERY,@ParamDefinition,@TableName,@Brief,@Full,@CreatedBy,@Department,@Answer,@Id;
-- exec version
SET @SQLQUERY = 'UPDATE ' + @TableName + ' SET
Brief ='+ @Brief+',
[Full] ='+ @Full+',
CreatedBy ='+ @CreatedBy+',
Department ='+ @Department+',
Answer ='+@Answer+' WHERE Id='+CAST(@Id as nvarchar(10))
print @SQLQUERY;
EXEC (@SQLQUERY)
我已使用EXEC
和sp_executesql
程序执行我的动态查询,但两者都失败了。
如果EXEC
动态查询未设置为@SQLQUERY
变量(在调试后看到),在sp_executesql
的情况下,虽然数据库已更新,但我得到标量变量错误已经把所有东西都传给了它。
答案 0 :(得分:6)
案例非常简单。您无法在UPDATE
语句中对表/列名称进行参数化:
SET @SQLQUERY = 'UPDATE @TableName --here is problem
SET Brief = @Brief,
[Full] = @Full,
CreatedBy = @CreatedBy,
Department = @Department,
Answer = @Answer
WHERE Id=@Id';
SET @ParamDefinition=N'@TableName nvarchar(50),@Brief nvarchar(50),
@Full nvarchar(MAX), @CreatedBy varchar(256),
@Department varchar(256),@Answer nvarchar(MAX),@Id int'
EXEC dbo.sp_executesql @SQLQUERY,@ParamDefinition,
@TableName,@Brief,@Full,
@CreatedBy,@Department,@Answer,@Id;
改为使用替换:
SET @SQLQUERY = N'UPDATE <tab_name>
SET Brief = @Brief,
[Full] = @Full,
CreatedBy = @CreatedBy,
Department = @Department,
Answer = @Answer
WHERE Id = @Id';
SET @SQLQUERY = REPLACE(@SQLQUERY, '<tab_name>', QUOTENAME(@TableName));
SET @ParamDefinition=N'@Brief nvarchar(50),@Full nvarchar(MAX),
@CreatedBy varchar(256),@Department varchar(256),
@Answer nvarchar(MAX),@Id int';
EXEC [dbo].[sp_executesql] @SQLQUERY,
@ParamDefinition,
@Brief,@Full,@CreatedBy, @Department,@Answer,@Id;
注意:
SYSNAME
数据类型。QUOTENAME
引用标识符(以避免潜在的SQL注入攻击)。@CreatedBy
datetime
就是为什么我不明白为什么它会以varchar(256)
传递。;
结束每个语句。在将来的版本中,这将是强制性的。