从临时表插入表

时间:2022-09-24 15:42:54

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:

#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值插入到表测试中。

1 个解决方案

#1


17  

You could use an insert-select statement:

您可以使用insert-select语句:

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

#1


17  

You could use an insert-select statement:

您可以使用insert-select语句:

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