Insert into table from temporary table

泪湿孤枕 提交于 2019-12-06 18:09:38

问题


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.


回答1:


You could use an insert-select statement:

INSERT INTO test
SELECT @col1, @col2, col3
FROM   #temp


来源:https://stackoverflow.com/questions/27445247/insert-into-table-from-temporary-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!