IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_warehouse_operation_detail_delete]') AND type = 'TR')
DROP TRIGGER [dbo].[mps_warehouse_operation_detail_delete]
GO
create trigger [dbo].[mps_warehouse_operation_detail_delete] on [dbo].[mps_warehouse_operation_detail] for delete as
begin
    declare
       @numrows  int,
       @errno    int,
       @errmsg   varchar(255)

    select  @numrows = @@rowcount
    if @numrows = 0
       return

-- 仓库数据还原 
declare @t table(whgid  bigint, amount decimal(18,4),fee decimal(18,4),opr int , base decimal(18,4) , inamount decimal(18,4),infee decimal(18,4) , outamount decimal(18,4),outfee decimal(18,4)) 
insert into @t(whgid,amount,fee,base,inamount,infee,outamount,outfee) 
select whopd_whgid,SUM(whopd_amount*whopd_operation),SUM(whopd_fee*whopd_operation),SUM(whopd_baseamount*whopd_operation) ,
SUM(whopd_amount*case when whopd_operation=1 then 1 else 0 end),SUM(whopd_fee*case when whopd_operation=1 then 1 else 0 end) ,
SUM(whopd_amount*case when whopd_operation=-1 then 1 else 0 end),SUM(whopd_fee*case when whopd_operation=-1 then 1 else 0 end)  
from deleted 
group by whopd_whgid 

update mps_warehouse_data set 
whg_amount = whg_amount - amount ,
whg_baseamount = whg_baseamount - base ,
whg_fee = whg_fee - fee  ,
whg_inamount = whg_inamount - inamount ,
whg_infee = whg_infee - infee ,
whg_outamount=whg_outamount - outamount ,
whg_outfee=whg_outfee - outfee 
from @t 
where whg_id=whgid 

    return

/*  Errors handling  */
error:
    -- raiserror @errno @errmsg
    rollback  transaction
end