I am creating stored procedure in which I need to build a temporary table dynamically. I tried the following code but its not creating table. When I execute the generated Query in Query window it works fine there.
--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)
Final generated create table Query is as follow
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)
Object #final used in CREATE and SELECT statements is not in the same scope.
Here is one way to structure the query.
Try to terminate SQL statements with semicolon. Even though it is not mandatory, it will help you differentiate the statements for readability. Note that I have included semicolon at the end of CREATE, INSERT and SELECT statements.
You can notice that CREATE, INSERT and SELECT are executed in the same transaction. Thereby, you don’t lose the scope of the temporary table.
Script:
Output: