我正在尝试使用临时动态查询将数据插入表变量中,然后使用该表变量执行最终查询。我有一个错误“必须声明标量变量”
submit
预期结果应该是:
TableName
变量@A_X可以有1或15个变量(@ A_1,@ A_2 .... @ A15)
答案 0 :(得分:0)
可以使用临时表代替表变量。检查一下:
DROP TABLE #TableList
GO
CREATE TABLE #TableList (
A_1 NVARCHAR(250)
,A_2 NVARCHAR(250)
,A_3 NVARCHAR(250)
)
DROP TABLE #Result
GO
CREATE TABLE #Result (
TableName NVARCHAR(250)
)
INSERT INTO #TableList
VALUES('ABC','XYZ','AEI')
DECLARE @q NVARCHAR(MAX)='';
DECLARE @i as int = 1
WHILE (@i <= 3)
BEGIN
SET @q = @q+CHAR(13)+'
INSERT INTO #Result(TableName)
SELECT A_' + CAST(@i AS VARCHAR) + ' from #TableList;'
SET @i = @i + 1
END
EXEC sp_executesql @q
PRINT (@q)
SELECT *
FROM #Result