0

I'm trying to automatically update a table when new rows have been inserted but my trigger is just putting null results into the table.

Basically I want to make CampaignID = CampaignID in the Signals table

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
2
  • am surprised that sql server allowed you to create a trigger with that syntax Commented Apr 13, 2018 at 15:57
  • 2
    this assumes lots of things....one being that you always insert one row into that table Commented Apr 13, 2018 at 15:57

1 Answer 1

2

Assuming that I understand your trigger correctly, then a far better solution would be:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.