SQL處理庫存與銷售,先進先出原則
阿新 • • 發佈:2019-02-01
--庫存表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)
@namevarchar(50),
@costint--,--銷售量
--@returns int output --該貨物的庫存是否夠(不夠:-1;夠:1)as--先得出該貨物的庫存是否夠declare@sparefloat
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
endendfrom t a where name=@nameand j!=c
endelseraiserror('庫存不足',16,1)
returngo--測試:exec wsp @name='A',@cost=390select*from t
--刪除測試環境droptable t
dropproc wsp