SQL 从临时表插入表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27445247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert into table from temporary table
提问by MAK
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 表插入。
#Temp:
#温度:
create table #temp
(
col3 varchar(30)
);
#Temp: Contains
#Temp:包含
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.
注意:变量值必须重复,直到#temp 值插入到表测试中。
回答by Mureinik
You could use an insert-select statement:
您可以使用插入选择语句:
INSERT INTO test
SELECT @col1, @col2, col3
FROM #temp