Is there a way to create a table from a complex query result set? A parameter will contain a query and I need to take this query and put the result into a temporary table.
I have it working for a simple query
Declare @Src nvarchar(4000)='Select Distinct a,b,c from mytable'
Declare @newId VARCHAR(50)
SELECT @newId = REPLACE(CONVERT(VARCHAR(50),NEWID()),'-','')
-- Make sure the table doesn't exist... if does we need to delete it.
IF OBJECT_ID('TMP_' + @newId) IS NOT NULL
BEGIN
SET @SQLStr = 'DROP TABLE TMP_' + @newId
EXEC (@SQLStr)
END
-- I might need the structucture or the result set or the results in the tmp table.
SET @SQLStr = 'SELECT * INTO TMP_' + @newId + ' FROM (' + @SRC + ') S WHERE 1=0'
EXEC(@SQLStr)
but what if @src
is with an 'order by' or with subqueries
Select a,b,c from mytable order by a,b
I would need to find the "from" and add "into 'TMP_' + @newId ' in front of it but it isn't safe as you can have subqueries in the fields portion of a select.
I tried to use the sp_describe_first_result_set @Tsql=@Src
, but as far as I know, I would need to parse the results in a cursor to build a create table statement, execute it, so that I can then insert the complex query using:
EXEC('Inset into tmp_'+ @newId + '
exec('+@src+')');
Any other way to simplify this? I'm trying to find a solution that will work for all version SQL servers (express or Standard).