Create Table tb(tid int,sl int,tdate datetime)
Insert into tb
Select 1,10,'2009-11-9' union all
Select 1,5,'2009-11-10' union all
Select 1,100,'2009-11-11'
一种商品出库,如果出库数量小于10,直接从最小的日期减掉,其他的不变;假如出库数量(sl)为20,首先出的是最小的日期,最小的日期数量不够往后减少第二个日期对应的数量,以此类推。如果出库为20,更新后的结果如下:1,0,'2009-11-9'
1,0,'2009-11-10'
1,95,'2009-11-11'
Insert into tb
Select 1,10,'2009-11-9' union all
Select 1,5,'2009-11-10' union all
Select 1,100,'2009-11-11'
一种商品出库,如果出库数量小于10,直接从最小的日期减掉,其他的不变;假如出库数量(sl)为20,首先出的是最小的日期,最小的日期数量不够往后减少第二个日期对应的数量,以此类推。如果出库为20,更新后的结果如下:1,0,'2009-11-9'
1,0,'2009-11-10'
1,95,'2009-11-11'
只用一条SQL不好实现吧,
因为中间有不少逻辑.
用存储过程可以实现
下面是我的一点思路
看看合适吗drop table pro
Create Table pro(tid int,sl int,tdate datetime)
Insert into pro
Select 1,10,'2009-11-9' union all
Select 1,5,'2009-11-10' union all
Select 1,100,'2009-11-11'
Create Procedure compute
--出库的数目
@cou int
AS
BEGIN
while 1=1
BEGIN
--先将同一产品的库存信息按先后排好序,取得最先要出库的记录
declare @sl int set @sl=(select top 1 sl from pro where tid='1' and sl > 0)
--考虑到可能库存小于要出库的情况(@cou > 库存的总数)
declare @i int set @i=(select count(*) from pro where tid='1' and sl > 0)
--库存已空(@cou > 库存总数) 或 正常出库完毕(@cou <= 库存总数),处理停止
if @i=0 or @cou=0
break;
--当前记录需要全部出库
if @sl <= @cou
BEGIN
--当前记录全部出库,记录更新为0
update pro set sl=0 where tid=(select top 1tid from pro where tid='1' and sl > 0)
and tdate=(select top 1tdate from pro where tid='1' and sl > 0)
set @cou=@cou-@sl
--print @cou
END
--当前库存记录足以出库用
else
BEGIN
--当前记录全部出库,记录更新为剩余数目
update pro set sl=@sl-@cou where tid=(select top 1tid from pro where tid='1' and sl > 0)
and tdate=(select top 1tdate from pro where tid='1' and sl > 0)
set @cou=0
END
END
END
--调用存储过程
EXEC compute 100
Insert into tb
Select 1,10,'2009-11-9' union all
Select 1,5,'2009-11-10' union all
Select 1,100,'2009-11-11' declare @sl int
set @sl=13 -- 出库量
while @sl > 0
update tb set @sl=@sl-sl, sl=(case when @sl>=0 then 0 else abs(@sl) end)
where tdate=(select min(tdate) from tb where sl>0)
Insert into tb
Select 1,10,'2009-11-9' union all
Select 1,5,'2009-11-10' union all
Select 1,100,'2009-11-11' declare @sl int
set @sl=13
while @sl > 0
update tb set @sl=@sl-sl, sl=(case when @sl>=0 then 0 else abs(@sl) end)
where tdate=(select min(tdate) from tb where sl>0)select * from tb
/*
1 0 2009-11-09 00:00:00.000
1 2 2009-11-10 00:00:00.000
1 100 2009-11-11 00:00:00.000
*/