动态SQL选择变量名称

时间:2019-03-27 10:27:16

标签: sql sql-server

我有以下SQL语句,效果很好:

DECLARE @TableName VARCHAR(250);
SET @TableName = 'TBL_Name'
SELECT QUOTENAME(@TableName) As TableName, HASHBYTES('SHA1', (SELECT * FROM TBL_Name FOR XML RAW)) As TableHash

我现在希望能够将表名作为变量传递,因此我可以将其用作函数,所以我尝试了以下方法:

DECLARE @TableName VARCHAR(250);
SET @TableName = 'TBL_Name'
EXEC('SELECT QUOTENAME(' + @TableName + ') As TableName, HASHBYTES(''SHA1'', (SELECT * FROM TBL_NameFOR XML RAW)) As TableHash');

运行此命令时,出现以下错误:

Invalid column name 'TBL_Name'.

如果我删除列名并将其更改为该名称,它将起作用:

DECLARE @TableName VARCHAR(250);
SET @TableName = 'TBL_Name'
EXEC('SELECT HASHBYTES(''SHA1'', (SELECT * FROM ' + @TableName + ' FOR XML RAW)) As TableHash');

我的问题是,如何获取查询以将表名称输出为列?

1 个答案:

答案 0 :(得分:1)

QUOTENAME函数具有第二个可选参数,用于将值包装为其他字符,在这种情况下,您需要使用单引号将@TableName用作首次使用的varchar值,并将其用作表名。第二个

DECLARE @TableName NVARCHAR(250);
SET @TableName = N'TBL_Name'
DECLARE @SQL NVARCHAR(MAX) = N'SELECT ' + QUOTENAME(@TableName,'''') + N' as TableName, HASHBYTES(''SHA1'', (SELECT * FROM ' + QUOTENAME(@TableName) + N' FOR XML RAW)) As TableHash'
EXEC(@SQL);

它将创建以下代码

SELECT 'TBL_Name' as TableName, HASHBYTES('SHA1', (SELECT * FROM [TBL_Name] FOR XML RAW)) As TableHash