有类似于下表的
订货表
货号 客人 订货数
A001 C001 100
A001 C002 50
A001 C003 200
入库表
货号 入库
A001 180
A002 300
我要在存储过程中实现,把A001的入库400个的数量,分配到订货表中
货号 客人 订货数 分配库存数
A001 C001 100 100
A001 C002 50 50
A001 C003 200 30
数据库是SQL2000,这必须用游标做么?如果不用游标循环有没有什么更好的办法实现呢?
------解决方案--------------------
看了一下 估计只能用游标了。
------解决方案--------------------
不用游标的方法,
create table 订货表
(货号 varchar(10),客人 varchar(10),订货数 int)
insert into 订货表
select 'A001','C001',100 union all
select 'A001','C002',50 union all
select 'A001','C003',200
create table 入库表
(货号 varchar(10),入库 int)
insert into 入库表
select 'A001',180 union all
select 'A002',300
select 货号,客人,订货数,identity(int,1,1) 'rn'
into #dh
from 订货表
select 货号,客人,订货数,
(select sum(b.订货数)
from #dh b
where b.货号=a.货号 and b.rn<=a.rn) 'qty'
into #dh2
from #dh a
select a.货号,a.客人,a.订货数,
case when b.入库>=a.qty then a.订货数
when b.入库>(a.qty-a.订货数) then b.入库-(a.qty-a.订货数)
else 0 end '分配库存数'
from #dh2 a
inner join 入库表 b on a.货号=b.货号
/*
货号 客人 订货数 分配库存数
---------- ---------- ----------- -----------
A001 C001 100 100
A001 C002 50 50
A001 C003 200 30
(3 row(s) affected)
*/