Dynamic query results into a temp table or table variable

萝らか妹 提交于 2019-12-02 02:27:58
SausageFingers

I have found a solution that works for me with the help of @SQLMenace in this post T-SQL Dynamic SQL and Temp Tables

In short, I need to create a #temp table in normal SQL first, then I can alter the structure using further dynamic SQL statements. In this example @colcount is set to 6. This will be determined by another stored proc when I implement this.

IF object_id('tempdb..#myTemp') IS NOT NULL
DROP TABLE #myTemp

CREATE TABLE #myTemp (id int IDENTITY(1,1) )
DECLARE @cmd nvarchar(max)
DECLARE @colcount int
SET @colcount = 6
DECLARE @counter int
SET @counter = 0
WHILE @counter < @colcount
    BEGIN
      SET @counter = @counter + 1
      SET @cmd = 'ALTER TABLE #myTemp  ADD col' + CAST(@counter AS varchar(4)) + ' NVARCHAR(MAX)'
      EXEC(@cmd)
    END

INSERT INTO #myTemp 
EXEC myProc @param1, @param2, @param3

SELECT * FROM #myTemp

IS there any reason you can't do something like:

SELECT *
INTO #MyTempTable
FROM MyResultSet

SELECT INTO doesn't require an explicit field list.

You can use global temp tables whose names are 'uniquified' by the SPID of the creating process. This can allow you to avoid stomping on other global temp tables created by other connections.

Just make sure to clean them up when you're done... :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!