存储过程 根据a,b表添加更新c表.~~~~~~~~~~~~~~~~~~

caoqinghua 2004-11-22 11:38:45
如题

数据库表如下
a 表
序号 所属单位 所属供应商
1 xxxx yyyy
2 cccc zzzz
3 bbbb hhhh

b 表
序号 货物 规格 计量单位 批号 货物失效日期 数量
1 a x z 20010101 2001-11-01 10
1 b x z 20010101 2001-11-01 20

2 c y q 20030506 2003-05-06 10
2 d w 5 20030506 2003-05-06 200

c 表
流水号 所属单位 所属供应商 货物 规格 计量单位 批号 货物失效日期 数量
1 xxxx yyyy a x z 20010101 2001-11-01 100

a 表中的序号和b 表中的序号是1对多的关系

我根据传递的"序号"参数 把 a,b表中的数据更新或者添加到 c 表中
1)如果c表中存在 相同的单位,相同的供应商,相同货物,相同批号 的数据,则 更新c表中的数量
2)如果 c表中没有 相同的单位,相同的供应商,相同货物,相同批号 的数据, 则,根据a,b表添加
到c表

help me

...全文
138 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
八爪鱼-杭州 2004-11-23
  • 打赏
  • 举报
回复
select 流水号, 货物, 规格, 计量单位, 批号,货物失效日期,数量,
所属单位=(select 所属单位 from a where a.序号 = b.序号) ,
所属供应商=(select 所属供应商 from a where a.序号 = b.序号)
into #t
from b


insert into c(流水号, 货物, 规格, 计量单位, 批号,货物失效日期,数量,所属单位,所属供应商)
select 流水号, 货物, 规格, 计量单位, 批号,货物失效日期,数量,所属单位,所属供应商
from #t as t1,c as t2
where t1.流水号!=t2.流水号 or t1.货物!=t2.货物 or....

update c
set 数量=数量+select isnull( (select sum(数量) from #t where
where t1.流水号=t2.流水号 and t1.货物=t2.货物... ))
Angelnet 2004-11-23
  • 打赏
  • 举报
回复
收藏
qizhanfeng 2004-11-23
  • 打赏
  • 举报
回复
邹建的对
caoqinghua 2004-11-23
  • 打赏
  • 举报
回复
谢谢各位,zjsen(星愿) zjcxc(邹建) davorsuker39(大狐狸)
一会儿揭贴
zjcxc 元老 2004-11-23
  • 打赏
  • 举报
回复
应该先更新,再插入的,否则插入的数据也会被更新一次,降低了效率
davorsuker39 2004-11-23
  • 打赏
  • 举报
回复
select 流水号, 所属单位=(select 所属单位 from a where a.序号 = b.序号) ,
所属供应商=(select 所属供应商 from a where a.序号 = b.序号),货物, 规格, 计量单位, 批号,货物失效日期,数量
into #table
from b ---------使用中间表过渡
insert into c(流水号, 所属单位,所属供应商,货物, 规格, 计量单位, 批号,货物失效日期,数量)
select 流水号, 所属单位,所属供应商,货物, 规格, 计量单位, 批号,货物失效日期,数量
from #table as t1,c as t2
where t1.所属供应商<>t2.所属供应商 and t1.货物<>t2.货物 and t1.计量单位<>t2.计量单位 and t1.批号<>t2.批号
update c
set 数量=数量+(select isnull(sum(数量),0) from #table a where t1.所属供应商=t2.所属供应商 and t1.货物=t2.货物 and t1.计量单位=t2.计量单位 and t1.批号=t2.批号)
zjcxc 元老 2004-11-23
  • 打赏
  • 举报
回复
--处理的存储过程
create proc p_process
@序号 int
as
set xact_abort on
begin tran
--先更新已经存在的
update c set 数量=b.数量
from a,b,c
where a.序号=@序号 and b.序号=@序号 and a.序号=b.序号
and a.所属单位=c.所属单位 and a.所属供应商=c.所属供应商
and b.货物=c.货物 and b.批号=c.批号

--插入不存在的
insert c(所属单位,所属供应商,货物,规格,计量单位,批号,货物失效日期,数量)
select a.所属单位,a.所属供应商,b.货物,b.规格,b.计量单位,b.批号,b.货物失效日期,b.数量
from a,b,c
where a.序号=@序号 and b.序号=@序号 and a.序号=b.序号
and not exists(
select * from c
where a.所属单位=c.所属单位 and a.所属供应商=c.所属供应商
and b.货物=c.货物 and b.批号=c.批号)

34,591

社区成员

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

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