[sql] TSQL select into Temp table from dynamic sql

This seems relatively simple, but apparently it's not.

I need to create a temp table based on an existing table via the select into syntax:

SELECT * INTO #TEMPTABLE FROM EXISTING_TABLE

The problem is, the existing table name is accepted via a parameter...

I can get the table's data via:

execute ('SELECT * FROM ' + @tableName)

but how do I marry the two so that I can put the results from the execute directly into the temp table.

The columns for each table that this is going to be used for are not the same so building the temp table before getting the data is not practical.

I'm open to any suggestions except using a global temp table.

Update:

This is completely ridiculous, BUT my reservations with the global temp table is that this is a multi user platform lends itself to issues if the table will linger for long periods of time...

Sooo.. just to get past this part I've started by using the execute to generate a global temp table.

execute('select * into ##globalDynamicFormTable from ' + @tsFormTable) 

I then use the global temp table to load the local temp table:

select * into #tempTable from ##globalDynamicFormTable

I then drop the global table.

drop table ##globalDynamicFormTable

this is dirty and I don't like it, but for the time being, until i get a better solution, its going to have to work.

In the End:

I guess there is no way to get around it.

The best answer appears to be either;

Create a view in the execute command and use that to load the local temp table in the stored procedure.

Create a global temp table in the execute command and use that to load the local temp table.

With that said i'll probably just stick with the global temp table because creating and dropping views is audited in my organization, and I'm sure they are going to question that if it starts happening all the time.

Thanks!

This question is related to sql sql-server tsql temp-tables

The answer is


Take a look at OPENROWSET, and do something like:

SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
     , 'Server=(local)\SQL2008;Trusted_Connection=yes;',
     'SELECT * FROM ' + @tableName)

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

DECLARE @count_ser_temp int;
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'TableTemporal'

EXECUTE ('CREATE VIEW vTemp AS
    SELECT *
    FROM ' + @TableTemporal)
SELECT TOP 1 * INTO #servicios_temp  FROM vTemp

DROP VIEW vTemp

-- Contar la cantidad de registros de la tabla temporal
SELECT @count_ser_temp = COUNT(*) FROM #servicios_temp;

-- Recorro los registros de la tabla temporal 
WHILE @count_ser_temp > 0
 BEGIN
 END
END

declare @sql varchar(100);

declare @tablename as varchar(100);

select @tablename = 'your_table_name';

create table #tmp 
    (col1 int, col2 int, col3 int);

set @sql = 'select aa, bb, cc from ' + @tablename;

insert into #tmp(col1, col2, col3) exec( @sql );

select * from #tmp;

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to temp-tables

How to find difference between two columns data? Temporary table in SQL server causing ' There is already an object named' error SQL Server Creating a temp table for this query Create a temporary table in MySQL with an index from a select How can I simulate an array variable in MySQL? When should I use a table variable vs temporary table in sql server? Inserting data into a temporary table TSQL select into Temp table from dynamic sql dropping a global temporary table Is there a way to get a list of all current temporary tables in SQL Server?