Handling multiple records in a MS SQL trigger

前端 未结 5 486
猫巷女王i
猫巷女王i 2020-12-13 16:43

I am having to use triggers in MSSQL for the first time, well triggers in general. Having read around and tested this myself I realise now that a trigger fires per command a

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 17:03

    Your best bet is to move to a set based operation in the trigger. I'm not going write this for you 100% but let me get you started, and we can see where we go from there. Keep in mind I am writting this without tables / schemas and so I'm not going validate. Expect Typos:-)

    Let's look at your update statements first, From what I can tell you are updating the same table with the same where clause the only difference is the columns. You can consolidate this to look like:

    UPDATE CachedStats SET
            /* Basically we are going to set the counts based on the type inline in the update clause*/
    
        Leads= CASE WHEN (@Type = 1 OR  @Type = 4 OR @Type=3 ) THEN Leads + 1 ELSE LEADS END,
            Clicks=CASE WHEN (@Type=0) THEN Clicks+1 ELSE Clicks END,
        Views=CASE WHEN (@Type=4) THEN Views+1 ELSE Views END,
            PublisherEarning = @PublisherEarning + PublisherEarning,
            AdvertiserCost = @AdvertiserCost +AdvertiserCost,
    FROM CachedStats CS
    INNER JOIN Inserted INS
        ON CS.Date=Inserted.Date AND CS.CustomerId=Ins.PublisherId AND CS.CampaignId=Ins.CampaignId      
    

    I do aggree with you that this could get ugly but that's a decision you'll have to make.

    As for your insert clause, I would handle that the same way you already are just insert into the table from the Inserted table whatever doesn't already exist.

提交回复
热议问题