1. 程式人生 > >SQL處理庫存與銷售,先進先出原則

SQL處理庫存與銷售,先進先出原則

--庫存表createtable t( id intidentity(1,1),
name
varchar(50),--商品名稱j int, --入庫數量c int,        --出庫數量jdate datetime--入庫時間)
insertinto t(name,j,c,jdate) select'A',100,0,'2007-12-01'insertinto t(name,j,c,jdate) select'A',200,0,'2008-01-07'insertinto t(name,j,c,jdate) select'B',320,0,'2007-12-21'insertinto t(name,j,c,jdate)

select'A',100,0,'2008-01-15'insertinto t(name,j,c,jdate) select'B',90,0,'2008-02-03'insertinto t(name,j,c,jdate) select'A',460,0,'2008-02-01'insertinto t(name,j,c,jdate) select'A',510,0,'2008-03-01'gocreateproc wsp
@namevarchar(50),
@costint--,--銷售量
--
@returns int output --該貨物的庫存是否夠(不夠:-1;夠:1)as--先得出該貨物的庫存是否夠declare@sparefloat
--剩餘庫存select@spare=sum(j)-sum(c) from t where name=@nameif(@spare>=@cost)
begin--根據入庫日期採用先進先出原則對貨物的庫存進行處理update t set c=casewhen (select@cost-isnull(sum(j),0)+isnull(sum(c),0) from t where name=@nameand jdate<=a.jdate and j!=c)>=0then a.j
   
elsecasewhen (select@cost-isnull(sum(j),0)+isnull(sum
(c),0) from t where name=@nameand jdate<a.jdate and j!=c)<0then0else (select@cost-isnull(sum(j),0)+isnull(sum(c),0)+a.c from t where name=@nameand jdate<a.jdate and j!=c)
       
endendfrom t a where name=@nameand j!=c
endelseraiserror('庫存不足',16,1)   
   
returngo--測試:exec wsp @name='A',@cost=390select*from t

--刪除測試環境droptable t
dropproc wsp