你能在SQL中的触发器中设置一个变量来等于另一个表中的变量吗?

时间:2018-04-13 15:56:07

标签: sql sql-server triggers

我尝试在插入新行时自动更新表,但我的触发器只是将null结果放入表中。

基本上我想在CampaignID = CampaignID

中制作Signals
ALTER TRIGGER UpdateSignalCounts
ON Signals
AFTER INSERT 
AS 
    DECLARE @CampaignID INT

    SET @CampaignID FOR SELECT CampaignID FROM Signals
BEGIN
    INSERT INTO SignalCounts (NumberRecieved, NumberOpened, NumberClicked, NumberForwarded, NumberUnsubscribed, NumberBounced, CampaignID)
       (SELECT 
            COUNT(Recieved), COUNT(Opened), COUNT(Clicked), COUNT(Forwards), 
            COUNT(Unsubscribed), COUNT(Bounced), @CampaignID 
        FROM 
            Signals 
        WHERE 
            CampaignID = @CampaignID);
END

1 个答案:

答案 0 :(得分:2)

假设我正确理解了你的触发器,那么一个更好的解决方案是:

ALTER TRIGGER UpdateSignalCounts ON Signals
AFTER INSERT AS 
BEGIN

    INSERT INTO SignalCounts(NumberRecieved,NumberOpened,NumberClicked,NumberForwarded,NumberUnsubscribed,NumberBounced, CampaignID)
    SELECT COUNT(Recieved),
           COUNT(Opened),
           COUNT(Clicked),
           COUNT(Forwards),
           COUNT(Unsubscribed),
           COUNT(Bounced)
           S.CampaignID
    FROM Signals S
    WHERE S.CampaignID IN (SELECT i.CampaignID
                           FROM inserted)
    GROUP BY S.CampaignID;

END