I am creating a SQL Query dynamically. After it's been created I want to execute it and store it as a temporary table.
WITH [VALIDACCOUNTS] AS( EXEC (@sqlQuery))
I am creating a SQL Query dynamically. After it's been created I want to execute it and store it as a temporary table.
WITH [VALIDACCOUNTS] AS( EXEC (@sqlQuery))
You have two solutions for this:
As a first solution you can simply use an INSERT EXEC
. This will work if you have a specified result set. This could be used if your procedure just returns one result set with a fixed result design.
Simply create your temporary table with matching columns and datatypes. After that you can call this:
INSERT INTO #yourTemporaryTable
EXEC(@sql)
The second solution would be the usage of OPENROWSET
for this, which may have some sideeffects.
You can read more about it here.
INSERT INTO #yourTemptable
SELECT *
FROM OPENROWSET('SQLNCLI', 'DRIVER={SQL Server};',
'EXEC (''+@sql+''))'