我正在创建存储过程,我需要在其中动态构建一个临时表。我尝试了以下代码,但它没有创建表。当我在查询窗口中执行生成的查询时,它在那里工作正常。
--declare query variable
DECLARE @Query nvarchar(MAX)
SET @Query = 'CREATE TABLE #final (DATE int,'
--DECLARE @COLUMNNAME VARIABLE
DECLARE @ColName nvarchar(10)
OPEN @taCur
FETCH NEXT FROM @taCur INTO @ColName
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @Query = @Query + 'T_' + @ColName +' int,'
FETCH NEXT FROM @taCur INTO @ColName
END
SET @Query = @Query + 'TOTAL int,CUMM_TOTAL int)'
print @Query
EXEC sp_executesql @Query
--SET @Query = 'INSERT INTO #final (DATE) VALUES (1)'
SET @Query = 'SELECT * FROM #final'
print @Query
EXEC(@Query)
最终生成的创建表查询如下
CREATE TABLE #final (DATE int,T_211E int,T_211G int,T_211H int,T_211J int,T_211L int,T_221F int,TOTAL int,CUMM_TOTAL int)