首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

将一条表里的数据插入到另外一张表解决方法

2012-04-02 
将一条表里的数据插入到另外一张表一张表里的数据Tbl1idName1Name12Name2将Tbl1里面的数据插入到Tbl2里面。

将一条表里的数据插入到另外一张表
一张表里的数据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]goif object_id('[Tbl1]') is not null drop table [Tbl1]gocreate table [Tbl1]([id] int,[Name] varchar(5))goinsert [Tbl1]select 1,'Name1' union allselect 2,'Name2'gocreate table tbl2([id] int,[Name] varchar(5),Test varchar(4))insert tbl2select *,Test='test' from Tbl1select * from tbl2/*id    Name    Test1    Name1    test2    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)

热点排行
Bad Request.