mssql触发器demo
USE [pos]
GO
/****** Object: Trigger [dbo].[tr_insert] Script Date: 06/26/2014 09:27:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER TRIGGER [dbo].[tr_insert]
ON [dbo].[bill_d]
AFTER INSERT
AS
BEGIN
declare @goodsCode varchar(5)
declare @qty decimal(18,2)
declare @price money
declare @cnt int
declare @billType varchar(20)
declare @billNo varchar(20)
declare c1 cursor for select goodsCode,qty,price,billNo from inserted
open c1
FETCH NEXT FROM c1 INTO @goodsCode,@qty,@price,@billNo
WHILE @@FETCH_STATUS =0
begin
select @billType=billType from bill_m where billNo=@billNo
if @billType='StockIn' begin -- 进货
select @cnt=isnull(count(goodscode),0) from goods_stock where goodscode=@goodscode
if @cnt=0 begin
insert into goods_stock(goodscode,stock,price) values (@goodscode,@qty,@price)
end else begin
update goods_stock set stock=stock+@qty,price=(stock*price+@qty*@price)/(stock+@qty)
where goodscode=@goodscode
end
end else if @billType='StockInReturn' begin -- 进货退货
select @cnt=isnull(count(goodscode),0) from goods_stock where goodscode=@goodscode
if @cnt>0 begin
update goods_stock set stock=stock-@qty where goodscode=@goodscode
end
end
FETCH NEXT FROM c1 INTO @goodsCode,@qty,@price,@billNo
end
close c1
deallocate c1
END
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/3809394.html