I am writing a stored procedure (SQL Server) which receives string argument which represents a name of other stored procedure. This string also contains all the stored parameter so in order to run it I just need to write EXEC @vSpCommand
.
Now comes my problem: My procedure should be able to deal with versatile SPs so I can't know how will the result table would look like. Meaning I don't know how many columns the table would have, and the type of each column.
In addition inside the given SP (@vSpCommand
) there might be another dynamic call for other stored. Therefore using OPENROWSET
won't work. I have tried the following:
SET @vSpCommand = REPLACE(@vSpCommand,'''','''''')
SET @vCmd = 'IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[TA_SpTable'+@vExecId+']'') AND type in (N''U''))
DROP TABLE TA_SpTable'+@vExecId+' SELECT * INTO TA_SpTable'+ @vExecId+' FROM OPENROWSET(''SQLOLEDB'', ''Server=SERVERNAME,3180;Trusted_Connection=Yes'',
''EXEC '+@vSpCommand+ ''')'
EXEC (@vCmd)
Without any success.
The question is how do I insert this SP's result into table?
Unless it is not possible, solution is preferred within SQL, else using .NET CLR is also an option.
Transform your SP into a function then use SELECT INTO statement: