Hi @Sudip Bhatt ,
Storing the result into a Global Temporary Table is the best solution for your situation since your dynamic sql returns non deterministic columns.
If you would like to store dynamic sql result into #temporary table or a a table variable, you have to declare the DDL firstly which is not suitable for your situation.
Example of temporary table:
if object_id('tempdb..#t1') is not null drop table #t1
create table #t1(ID int)
declare @s varchar(max)
set @s='insert into #t1(ID)select number from master.dbo.spt_values where type=''P'' and number<10'
exec(@s)
insert into #t1(id)
exec('Select 1')
select * from #t1
Example of table variable:
DECLARE @t TABLE ( id INT )
DECLARE @q NVARCHAR(MAX) = 'declare @t table(id int)
insert into @t values(1),(2)
select * from @t'
INSERT INTO @t
EXEC(@q)
SELECT * FROM @t
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.