I know this isn't ideal, but I would like to know if it is possible to populate a temp table based on dynamic sql?
A very similar example to what I want to achieve is shown in this answer as either
SELECT into #T1 execute ('execute ' + @SQLString )
or
INSERT into #T1 execute ('execute ' + @SQLString )
I couldn't get either to work. It seems from the edit that the first option was wrong, so for the second option I've tried something like;
DECLARE @SQLString VARCHAR (2000) = 'SELECT * FROM INFORMATION_SCHEMA.COLUMNS'
INSERT into #MyTempTable execute (@SQLString )
Any ideas are much appreciated.
Edit:
In an attempt to clarify what I am trying to do without being too localised, I explain as briefly as I can below.
I have data in a staging area of my database that contains tables with dynamic names and a dynamic number of columns. However, a few of the column names are the same for each table. Rather than construct everything in dynamic sql, I would like to be able to simply extract the known columns into a temp table (or table variable, CTE, derived table or whatever) and act on that.
So given a table as so;
CREATE TABLE SomeParticularNameThatCantBeKnownToAStoredProc (
[1] AS VARCHAR(100),
[2] AS VARCHAR(100),
... -- Could be any number of these columns
[Id] AS INT,
[KnownCol] AS VARCHAR(100),
[KnownCol2] AS VARCHAR(100),
....
[DboId] AS INT
)
I'd like to be able to perform the necessary operations to allow my to process this data without having to do it all in dynamic sql. I was hoping to be able to do something like;
DECLARE @TableName AS VARCHAR(1000) = 'SomeParticularNameThatCantBeKnownToAStoredProc'
SELECT [Id], [KnownCol], [KnownCol2], [DboId]
INTO #KnownName
FROM @TableName -- I know this isn't possible, but this is what I'd like to do
This would then allow me to perform SQL statements against a consistent #KnownName. Some of the other operations I need to do are quite lengthy such as using the data to relate to other existing tables, copying data from the staging table(s) to their dbo schema equivalents and matching the DboId against the staging table Id using MERGE with OUTPUT INTO as described here, and so on and so forth.
If you can think of any other way I can limit the amount of dynamic SQL I need to write given the fact that the table name is dynamic then please let me know.