T-SQL过程,即使成功更新后标量变量也会出错

时间:2016-04-16 06:20:07

标签: sql sql-server tsql stored-procedures dynamic-sql

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

我已使用EXECsp_executesql程序执行我的动态查询,但两者都失败了。

如果EXEC动态查询未设置为@SQLQUERY变量(在调试后看到),在sp_executesql的情况下,虽然数据库已更新,但我得到标量变量错误已经把所有东西都传给了它。

1 个答案:

答案 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)传递。
  • 最好使用;结束每个语句。在将来的版本中,这将是强制性的。