动态sql中的局部变量用作前缀和值

时间:2017-05-17 23:10:16

标签: sql sql-server dynamic-sql

我使用局部变量滚动浏览不同的数据库。我试图使当前变量值出现在结果集中。当变量仅用作数据库前缀,但是当我从

更改硬编码数据库名称时,它可以正常工作
SET @sqlqueryNILS = 'SELECT ''A1'' AS SourceDB, NilConts FROM ' + @ODSname + '..MyTable'

SET @sqlqueryNILS = 'SELECT ' + @ODSname + ' AS SourceDB, NilConts FROM ' + @ODSname + '..MyTable'

无论我使用了多少引号,它都会失败并出现以下错误。

'Msg 207, Level 16, State 1, Line 1
Invalid column name 'A1'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'B2'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'C3''

查询:

CREATE TABLE #ODS_NILS(SourceDB NVARCHAR(6), NilConts INT)
CREATE TABLE A1..MyTable(NilConts INT)
INSERT INTO A1..MyTable SELECT 22
CREATE TABLE B2..MyTable(NilConts INT)
INSERT INTO B2..MyTable SELECT 24
CREATE TABLE C3..MyTable(NilConts INT)
INSERT INTO C3..MyTable SELECT 25

DECLARE @odslist TABLE (id INT IDENTITY(1,1),ODSDB NVARCHAR(20))                        
DECLARE @count INT = 1                      
DECLARE @total INT                      
INSERT INTO @odslist SELECT 'A1' UNION SELECT 'B2' UNION SELECT 'C3'                    

SELECT @total = MAX(id) FROM @odslist                       
WHILE @count <= @total                      
BEGIN                       
DECLARE @ODSname NVARCHAR(20), @sqlqueryNILS NVARCHAR(max)              
SELECT @ODSname = ODSDB FROM @odslist WHERE id = @count 


SET @sqlqueryNILS = 'SELECT ''A1'' AS SourceDB, NilConts FROM ' + @ODSname + '..MyTable'

INSERT INTO #ODS_NILS EXEC(@sqlqueryNILS)       
SET @sqlqueryNILS = NULL        
SET @count=@count+1;                
END;

SELECT * FROM #ODS_NILS

1 个答案:

答案 0 :(得分:0)

sqlqueryNILS是nvarchar所以

SET @sqlqueryNILS = N'SELECT