0

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))

1 Answers1

1

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+''))'
Ionic
  • 3,884
  • 1
  • 12
  • 33
  • 2 or more http://www.sommarskog.se/share_data.html, also note, these INSERT-EXEC bridges cannot be nested. Also, The `INTO` is optional, its inclusion is subjective. – Jodrell Jun 23 '15 at 08:04
  • Yes insert Exec cannot be nested, thats true. But the second exec is optional. – Ionic Jun 23 '15 at 08:35