求一存储过程。请会的朋友指点。最好给个代码。让我参照一下。

mark3625 2008-05-26 10:02:17
有两个表 表一 Person1 (ID,Name,Sex,other) 表二 person2(ID,Name,Sex,other) 利用表二的内容更新表一 SQL语句如何写。
比如Person1 ID,Name,Sex,other 数据是 1,小明,女, 山东
表二 数据是1,小明,“”,山东济南 ,2,小王,男,福建。
更新后的数据是:1,小明,女,山东济南
2,小王,男,福建
我的目的是根据数据库中的表二修改表一的内容。要求表二内中的如果有空的项就保留表一的内容。请朋友们帮忙。
...全文
87 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Limpire 2008-05-26
  • 打赏
  • 举报
回复
--> 测试数据: #1
if object_id('tempdb.dbo.#1') is not null drop table #1
create table #1 (ID int,Name varchar(4),Sex varchar(2),other varchar(8))
insert into #1
select 1,'小明','女','山东'
--> 测试数据: #2
if object_id('tempdb.dbo.#2') is not null drop table #2
create table #2 (ID int,Name varchar(4),Sex varchar(2),other varchar(8))
insert into #2
select 1,'小明','','山东济南' union all
select 2,'小王','男','福建'

update #1 set
Sex=case when b.Sex='' then a.Sex else b.Sex end,
other=case when b.other='' then a.other else b.other end
from #1 a join #2 b on a.id=b.id

insert #1 select * from #2 where not exists (select 1 from #1 where ID=#2.ID)

select * from #1
/*
ID Name Sex other
----------- ------ ----- --------
1 小明 女 山东济南
2 小王 男 福建
*/
being21 2008-05-26
  • 打赏
  • 举报
回复
触发器 是用来干这个的吧

触发器里面写

update 表二
set Sex = (select Sex from inserted)

你写存储过程不是要一直查询表一么?
dawugui 2008-05-26
  • 打赏
  • 举报
回复
update 表一
set Sex = isnull((select sex from 表二 where name = 表一.name),表一.sex),
other = isnull((select other from 表二 where name = 表一.name),表一.other)
dawugui 2008-05-26
  • 打赏
  • 举报
回复
有两个表
表一 Person1 (ID,Name,Sex,other)
表二 person2(ID,Name,Sex,other)
利用表二的内容更新表一 SQL语句如何写。
比如Person1 ID,Name,Sex,other 数据是 1,小明,女, 山东
表二 数据是1,小明,“”,山东济南
2,小王,男,福建。
更新后的数据是:1,小明,女,山东济南
2,小王,男,福建
我的目的是根据数据库中的表二修改表一的内容。要求表二内中的如果有空的项就保留表一的内容。请朋友们帮忙。

update 表一
set Sex = isnull((select sex from 表二 where name = 表一.name),表一.name),
other = isnull((select other from 表二 where name = 表一.name),表一.other)
Limpire 2008-05-26
  • 打赏
  • 举报
回复
update Person1 set
Sex=case when b.Sex='' then Sex else b.Sex end,
other=case when b.other='' then other else b.other end
from Person1 a join Person2 b on a.id=b.id

34,873

社区成员

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

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