sql server触发器写法

文章目录

      • 参考资料:
      • 示例

参考资料:

  1. https://social.msdn.microsoft.com/Forums/sqlserver/en-US/06d19955-5041-4f58-86f6-b5f1ada8b0d8/how-to-get-old-and-new-values-while-writing-triggers-in-sql-server-2005-or-2008?forum=transactsql
  2. http://www.cnblogs.com/rainman/p/3675834.html#m2
  3. https://docs.microsoft.com/en-us/sql/t-sql/language-elements/if-else-transact-sql?view=sql-server-2017
  4. http://www.cnblogs.com/yank/p/4193820.html
  5. https://www.cnblogs.com/hoojo/archive/2011/07/20/2111316.html

示例

--after update
create trigger tgr_lineitem_price_update
on Sales.LINEITEM
after update 
as begin
	if update(L_EXTENDEDPRICE) or update(L_DISCOUNT) or update(L_TAX) begin
		--定义所需变量,存储旧行和新行的值
		declare @L_valuediff Real
		declare @newEx Real
		declare @newDis Real
		declare @newTax Real
		declare @oldEx Real
		declare @oldDis Real
		declare @oldTax Real
		declare @newOrderkey int
		select @newEx = L_EXTENDEDPRICE from inserted
		select @newDis = L_DISCOUNT from inserted
		select @newTax = L_TAX from inserted
		select @oldEx = L_EXTENDEDPRICE from deleted
		select @oldDis = L_DISCOUNT from deleted
		select @oldTax = L_TAX from deleted
		select @newOrderkey = L_ORDERKEY from inserted
		
		--更新别的表的值
		set @L_valuediff = @newEx * (1-@newDis)*(1+@newTax) - 
						@oldEx * (1-@oldDis)*(1+@oldTax)
		update Sales.ORDERS set O_TOTALPRICE=O_TOTALPRICE+@L_valuediff
		where O_ORDERKEY = @newOrderkey
	end	
end
--instead of update
--sql server可以用instead of 来代替before触发器
create trigger tri_update
on Sales.LINEITEM
instead of update
as begin
	if update(L_QUANTITY) begin
		declare @L_valuediff int
		declare @L_availqty int
		declare @newQu int
		declare @newPa int
		declare @newSu int
		declare @oldQu int
		select @newQu = L_QUANTITY from inserted
		select @newPa = L_PARTKEY from inserted
		select @newSu = L_SUPPKEY from inserted
		select @oldQu = L_QUANTITY from deleted

		set @L_valuediff = @newQu - @oldQu

		select @L_availqty = PS_AVAILQTY from Sales.PARTSUPP
		where PS_PARTKEY = @newPa and PS_SUPPKEY = @newSu

		if (@L_availqty - @L_valuediff >= 0) begin
			--有可用的数量,满足订单订购数量
			print 'Available quantity is enough'
			update Sales.PARTSUPP
			set PS_AVAILQTY = PS_AVAILQTY-@L_availqty
			where PS_PARTKEY = @newPa and PS_SUPPKEY = @newSu
		end
		else
			print 'Available quantity is not enough'
	end
end

你可能感兴趣的:(sql)