码迷,mamicode.com
首页 > 其他好文 > 详细

一个内容丰富的存储过程

时间:2015-12-14 16:23:59      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

ALTER proc [dbo].[pro_inventory]--单据过账 
@orderno nvarchar(50),
@inout int--加还是减库存 用1,-1标示
as
declare @errorcount int

select @errorcount=COUNT(1) from yw_order where orderno=@orderno and ostate>0--只执行一次
if(@errorcount>0)
begin
RAISERROR(*此单据已经过账!,16,1)
return
end

 Set XAcT_ABORT ON --有错误马上回滚
   Begin Transaction T--开始事物
    
   select orderno,hid,cid,wid,cwid,wcode,wname,wguige,SUM(qty) as qty into #table0616 from yw_orderlist  where orderno=@orderno
   group by orderno,hid,cid,wid,cwid,wcode,wname,wguige
   
   
create table #table2054
(
    hid int,
    cid int,
    cangweiid int,
    materialid int,
    cqty int 
)
--将原库存里面有的物料从list表里面摘出来
insert into #table2054(hid,cid,cangweiid,materialid,cqty)
    select t1.hid,t1.cid,t1.cangweiid,t1.matreialid,t2.qty from YW_Inventory t1
    inner join #table0616 t2 on t1.cangweiid=t2.cwid and t1.cid=t2.cid and t1.hid=t2.hid and t1.matreialid=t2.wid
    where t2.orderno=@orderno
    

--先更新已有的库存信息
update YW_Inventory set YW_Inventory.cqty=YW_Inventory.cqty+b.cqty*@inout from #table2054 b where 
 YW_Inventory.cid=b.cid and YW_Inventory.hid=b.hid and yw_inventory.cangweiid=b.cangweiid and yw_inventory.matreialid=b.materialid 

select @errorcount = COUNT(1) from yw_inventory where cqty<0
if(@errorcount>0)
begin
Rollback Transaction T
RAISERROR(*系统不允许产生负库存,请核实,16,1)
return
end

--增加原来没有的-出库的地方 不会有insert的,有的话肯定有问题
insert into YW_Inventory(hid,cid,cangweiid,matreialid,cqty)
select t2.hid,t2.cid,t2.cwid,t2.wid,t2.qty*@inout
from #table0616 t2 where t2.orderno=@orderno and convert(varchar(10),t2.hid)+convert(varchar(10),t2.cid)+convert(varchar(10),t2.cwid)+convert(varchar(10),t2.wid) not in(select convert(varchar(10),hid)+convert(varchar(10),cid)+convert(varchar(10),cangweiid)+convert(varchar(10),materialid) from #table2054)

select @errorcount = COUNT(1) from yw_inventory where cqty<0
if(@errorcount>0)
begin
Rollback Transaction T
RAISERROR(*系统不允许产生负库存,请核实,16,1)
return
end 
--更改单据状态
 UPDATE yw_order SET ostate = 1 where orderno=@orderno
 update jc_cangwei set cwstate=1 where cwid in (select yw_orderlist.cwid from yw_orderlist where orderno=@orderno)
COMMIT Transaction T--提交
return 1

 

一个内容丰富的存储过程

标签:

原文地址:http://www.cnblogs.com/lilixiang-go/p/5045160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!