Fill table based on stored procedure with uncertain ordered columns

84 views Asked by At

I try to insert the outcome of a stored procedure into a table in SQL Server. It's part of something dynamic so what I do now is something like this:

SET @SQL = 'INSERT INTO [' + @DestinationTable + '](' + @fieldlist_target + ') EXEC ' + @SP

But the problem now is that @DestionationTable can be this structure:

ColumnA int  
ColumnB varchar(255)  
ColumnC datetime

And the stored procedure can (accidentally) output these 3 columns in a different order (by example start with ColumnC).

I've tried many things like inserting EXEC ' + @SP into a temp table or using it in a subquery so that I can do:

SET @SQL = 'INSERT INTO ['+@DestinationTable+']('+@fieldlist_target+') SELECT '+@fieldlist_target+' FROM #TableThatICanCreate

But this all doesn't work because of the fact that I have to define the temp table as well. And there is nothing that I can do to have the columns in the right order.

I've tried by example this:

DECLARE @fieldlist_datatype_target varchar(max) = (SELECT STRING_AGG(CONCAT([name], ' ', [system_type_name]), ', ') AS Name_DataType
    FROM sys.dm_exec_describe_first_result_set(CONCAT('EXEC ', @SP), null, 0))

This works as it should and fixes mainly my issue because @fieldlist_datatype_target then is filled with all the stored procedure output in the correct order. BUT this doesn't work for more exotic stored procedures like the one that use temp tables. Then sys.dm_exec_describe_first_result_set returns:

The metadata could not be determined because statement ... in procedure 'usp_...' uses a temp table.

So the question is: how to deal with this issue? I can't imagine I'm the only one but my whole search ends in 2 ways of doing this:

  1. Predefine temp table (which I now can't because of that sys.dm_exec_describe_first_result_set is not working always)
  2. Using OPENROWSET which I don't want to
0

There are 0 answers