I have a trigger that appears to work fine, however I want to make sure that it can handle multiple records in the inserted or deleted tables. Plus I few other questions.
The current trigger is something like
I have 3 questions.
1. Since my trigger is modifiying the table that initiates the Trigger, am I then causing another trigger to take place.
2. Is my method of recalling the IDENTITY value for inserted records legitimate? My identity key is Transactions.[ID]? Should I be using SCOPE_IDENTITY() ?
3. How do I make this trigger traverse throughout multiple records of the inserted and deleted tables.
Thank you.
The current trigger is something like
Code:
CREATE TRIGGER [SetData] ON dbo.Transactions
/*
The basic purpose of this trigger is to
1. Set the 'REF' column equal to the IDENTITY column when an new Transaction is Inserted and the Transaction type is a '0'
2. Automatically set a 'Cleared' bit in the invoice record if the sum of all payments is equal to the sum of the invoice.
*/
FOR INSERT, UPDATE, DELETE
AS
DECLARE @SumInv MONEY
DECLARE @SumPay MONEY
DECLARE @Ref INT
DECLARE @InvID INT
DECLARE @Type INT
DECLARE @Id INT
SET @Type = (Select [Type] from inserted)
SET @Id = (SELECT [ID] from inserted)
SET @Ref = (SELECT [REF] FROM inserted UNION SELECT [REF] FROM deleted)
/* Transactions that are Type 0 are invoices. For new invoices, I want to set the 'REF' column equal to the Identity column. */
IF EXISTS (SELECT * FROM inserted)
BEGIN
IF (@Type = 0)
BEGIN
UPDATE Transactions
SET REF = @Id
WHERE [ID] = @Id
SET @Ref = @Id
END
END
/* Find the Invoice ID. It's ID is equal to the REF and must be an Invoice (type = 0) */
SELECT @InvID = (SELECT dbo.Transactions.[ID]
FROM dbo.Transactions
WHERE (dbo.Transactions.[ID] = @Ref AND dbo.Transactions.[Type] = 0))
/* If the InvID is null, then it was deleted - so ignore everything. */
IF (@InvID IS NULL)
BEGIN
RETURN
END
SELECT @SumInv = (SELECT Amount
FROM dbo.Transactions
WHERE (dbo.Transactions.[ID] = @Ref))
SELECT @SumPay = (SELECT SUM(Amount)
FROM dbo.Transactions
WHERE (dbo.Transactions.REF = @Ref AND dbo.Transactions.[Type] > 0))
IF (@SumPay + @SumInv = 0)
BEGIN
UPDATE Transactions
SET [Invoice is Cleared] = 1
WHERE dbo.Transactions.[ID] = @InvID
END
ELSE
BEGIN
UPDATE Transactions
SET [Invoice is Cleared] = 0
WHERE dbo.Transactions.[ID] = @InvID
END
I have 3 questions.
1. Since my trigger is modifiying the table that initiates the Trigger, am I then causing another trigger to take place.
2. Is my method of recalling the IDENTITY value for inserted records legitimate? My identity key is Transactions.[ID]? Should I be using SCOPE_IDENTITY() ?
3. How do I make this trigger traverse throughout multiple records of the inserted and deleted tables.
Thank you.