简体   繁体   English

插入后的SQL触发器使用条件更新另一个表

[英]Sql Trigger After Insert Update another table with conditions

I am creating After Insert trigger , its working fine, but I have certain conditions before executing the statements inside the trigger 我正在创建After Insert触发器,它可以正常工作,但是在触发器内部执行语句之前我有一定条件

  1. Based on Different CustomerId Run the trigger, I want check which CustomerId got inserted in my LoyaltyDetailsTable, say if last insert was Customerid=2 then pass that Customerid in where condition then run the trigger , or if Customerid = 1 then run the trigger for that Id, so on. 根据不同的CustomerId运行触发器,我要检查在我的LoyaltyDetailsTable中插入了哪个CustomerId,说如果最后一次插入是Customerid = 2,则在该条件下传递该Customerid,然后运行触发器,或者如果Customerid = 1,然后为此运行触发器ID,依此类推。
  2. I want to check whether in PriceClaimTable the inserted CustomerId exist or not, If exists then update the details else just insert the values in LoyaltyDetailsTable only. 我想检查在PriceClaimTable中插入的CustomerId是否存在,如果存在则更新详细信息,否则仅在LoyaltyDetailsTable中插入值。

Trigger query 触发查询

CREATE TRIGGER DetailsAfterInsert ON [dbo].[LoyaltyDetailsTable]
FOR INSERT

as

UPDATE PriceClaimTable 
SET CurrentPoints = 
(  
(SELECT SUM(LoayaltyPointsTable.Points) AS RecentPoints FROM LoayaltyPointsTable
join LoyaltyDetailsTable ON LoayaltyPointsTable.LoyaltyPointsId 
= LoyaltyDetailsTable.LoyaltyPointsId
WHERE CustomerId=1 and LoyaltyDetailsId= (SELECT MAX(LoyaltyDetailsId)  
AS LoyaltyDetailsTable FROM LoyaltyDetailsTable))

+ 

(SELECT CurrentPoints FROM PriceClaimTable WHERE ClaimCustomerId=1 and 
PriceClaimId=(SELECT max(PriceClaimId) FROM PriceClaimTable
))

) 
WHERE ClaimCustomerId=1 and PriceClaimId=(SELECT max(PriceClaimId) FROM PriceClaimTable)

This is my first attempt to write a trigger, and here is table structure. 这是我第一次尝试编写触发器, 是表结构。

Any help would be great. 任何帮助都会很棒。

What you're looking for here is the inserted table. 您在这里寻找的是inserted表格。 Every time you issue an UPDATE statement, SQL Server generates two virtual tables called inserted and deleted that store information on the data modifications you're making. 每次发出UPDATE语句时,SQL Server都会生成两个称为inserteddeleted虚拟表,这些虚拟表存储有关您进行的数据修改的信息。 These tables are accessible from your trigger. 您可以通过触发器访问这些表。 For more information, see here: https://msdn.microsoft.com/en-us/library/ms191300.aspx 有关更多信息,请参见此处: https : //msdn.microsoft.com/zh-cn/library/ms191300.aspx

You can use inserted to get the IDs you're looking for. 您可以使用inserted获取所需的ID。 So, instead of: 因此,代替:

WHERE ClaimCustomerId=1

you can use: 您可以使用:

WHERE ClaimCustomerId=inserted.ClaimCustomerId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM