简体   繁体   中英

T-SQL Insert Column from Other Table

Hello I am trying to insert values from one table column to another table. I am using SQL Server 2008 R2 . Here is example:

Table 1

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

Table 2

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

I would like to insert file from Table 2 into Table 1 as well as some other static values.

So select * from table1 would end up looking like this:

File           Type        PartiesID

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

where the GW100, GW101, etc come from table2 and the 1 and 555 are static for every row.

I tried insert into table1 (file,type,partiesid) values (select file from table2,1,555) but that doesn't work. Is there a way where it will just insert a row for each unique file and also insert the static fields of 1 and 555 as separate columns?

Thanks!

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

You can try the below query:

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

This link gives you the format(s):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM