日期:2014-05-18  浏览次数:20457 次

将一条表里的数据插入到另外一张表
一张表里的数据Tbl1
id Name  

1 Name1
2 Name2

将Tbl1里面的数据插入到Tbl2里面。。但是Tbl2里面的Test列在Tbl1里面没有,
然后每列都插入固定的值 test

另外一张表里的数据Tb12

id Name Test

1 Name1 test
2 Name2 test


请问这条SQL语句应该怎么写?




------解决方案--------------------
insert t2
select *,Test='test' from t1
------解决方案--------------------
SQL code

--> 测试数据:[Tbl1]
go
if object_id('[Tbl1]') is not null 
drop table [Tbl1]
go
create table [Tbl1](
[id] int,
[Name] varchar(5)
)
go
insert [Tbl1]
select 1,'Name1' union all
select 2,'Name2'
go
create table tbl2(
[id] int,
[Name] varchar(5),
Test varchar(4)
)


insert tbl2
select *,Test='test' from Tbl1

select * from tbl2

/*
id    Name    Test
1    Name1    test
2    Name2    test
*/

------解决方案--------------------
如果存在对应的ID,则UPDATE
update tbl2 set test = 'test' from tbl2 t2 , tbl1 t1 where t2.id = t1.id

如果对应ID不存在,则需要insert
insert into tbl2 select id , name , 'test' from tbl1 t1 where not exists(select 1 from tbl2 t2 where t2.id = t1.id)