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

WIKESOFT
WIKESOFT 官方账号
2012-03-15 10:08:34
一张表里的数据Tbl1
id Name

1 Name1
2 Name2

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

另外一张表里的数据Tb12

id Name Test

1 Name1 test
2 Name2 test


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


...全文
187 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2012-03-15
  • 打赏
  • 举报
回复
如果存在对应的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)
  • 打赏
  • 举报
回复

--> 测试数据:[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
*/
  • 打赏
  • 举报
回复
insert t2
select *,Test='test' from t1

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧