T-SQL从另一个表插入列

时间:2014-03-20 06:28:27

标签: sql sql-server-2008 sql-server-2008-r2 sql-insert

您好我正在尝试将值从一个表列插入另一个表。我使用 SQL Server 2008 R2 。这是一个例子:

表1

Declare @Table1 table (file varchar(15), type int, partiesid int)

表2

Declare @Table2 table (file varchar(15), ....many other columns)

我想将表2中的文件插入表1以及其他一些静态值。

因此,从table1中选择*将最终看起来像这样:

File           Type        PartiesID

GW100          1           555
GW101          1           555
GW103          1           555
GW104          1           555

其中GW100,GW101等来自table2,而1和555对于每一行都是静态的。

我尝试插入table1(file,type,partiesid)值(从table2,1,555中选择文件),但这不起作用。有没有办法只为每个唯一文件插入一行,并将静态字段1和555作为单独的列插入?

谢谢!

3 个答案:

答案 0 :(得分:2)

Insert into @table2
(
file,
type,
partiesid,
...(other columns for which you need to give static values)
)
select 
file,
type,
partiesid,
...(static values for columns)
from @table1

答案 1 :(得分:0)

您可以尝试以下查询:

USE dbName
GO
INSERT INTO table2 (column_name(s))
SELECT column_name(s) FROM table1;
GO

答案 2 :(得分:0)

此链接为您提供以下格式:

http://www.w3schools.com/sql/sql_insert_into_select.asp