Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into table from temporary table

I have the following table:

Example:

create table test
(
 col1 varchar(10),
 col2 varchar(20),
 col3 varchar(30)
);

Now I want to insert two values by variables and last one by #temp table.

#Temp:

create table #temp
(
  col3 varchar(30)
);

#Temp: Contains

col3
-----
A1
A2
A3

Insertion into test table:

Declare @col1 varchar(10) = 'A'
Declare @col1 varchar(20) = 'B'
Declare @sql varchar(max)

SET @SQL = N'insert into test values('+@col1+','+@col2+',........); 
EXEC(@SQL)
/* How to insert `@col3` from #temp to test table*/

Expected Result:

col1   col2   col3
------------------
A      B      A1
A      B      A2
A      B      A3

Note: The variables values must repeat until the #temp values inserted into table test.

like image 928
MAK Avatar asked Dec 12 '14 13:12

MAK


People also ask

How do I insert a temp table into another table?

INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.

How do you add a temp table in SQL and insert values?

The general syntax would be like this: INSERT INTO temporary_tabel_name SELECT * FROM existing table_name; Following the general syntax, we will copy the data from the existing table, named, Guys into the newly created temporary table, named, “temporary_data”.


1 Answers

You could use an insert-select statement:

INSERT INTO test
SELECT @col1, @col2, col3
FROM   #temp
like image 80
Mureinik Avatar answered Sep 27 '22 21:09

Mureinik