我使用局部变量滚动浏览不同的数据库。我试图使当前变量值出现在结果集中。当变量仅用作数据库前缀,但是当我从
更改硬编码数据库名称时,它可以正常工作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
答案 0 :(得分:0)
sqlqueryNILS是nvarchar所以
SET @sqlqueryNILS = N'SELECT