Reputation: 15
Good day I have an external Program that stores information in SQL, I am trying to do a trigger that Updates a table when some of the fields in that Table change.
So I have one column Contractual Amount
that should be updated everytime any of the values in ufAPCHANG1EAMNT
, ufAPHANGE2AMNT
and ufAPCHANGE3AMNT
changes.
A person can change one or all of these values and can be either +ve or -ve then if they are any changes to those fields the Contractual Amount
should be updated accordingly but adding the +ve amount and subtracting the negative amount.
Please can you check my code and let me know where I am going wrong.
ALTER trigger [dbo].[trgContractualAmt]
ON [dbo].[Vendor]
AFTER UPDATE
AS
declare
@IdI integer,
@value1 decimal,
@Value2 decimal,
@value3 decimal,
@sum decimal,
@total decimal
SELECT
@IdI = i.DCLink,
@value1 = i.ufAPCHANGE1AMT,
@Value2 = i.ufAPCHANGE2AMNT,
@value3 =i.ufAPCHANGE3AMNT,
@total = i.ufAPContAmt
FROM
inserted i
BEGIN
IF TRIGGER_NESTLEVEL() > 1
RETURN
IF @value1 <> (select ufAPCHANGE1AMT from Vendor where DCLink = @IdI)
UPDATE Vendor
SET ufAPContAmt = ufAPContAmt + @value1
where DCLink = @IdI
if @Value2 <> (select ufAPCHANGE2AMNT from Vendor where DCLink = @IdI)
UPDATE Vendor
SET ufAPContAmt = ufAPContAmt + @value2
where DCLink = @IdI
if @Value3 <> (select ufAPCHANGE3AMNT from Vendor where DCLink = @IdI)
UPDATE Vendor
SET ufAPContAmt = ufAPContAmt + @value3
where DCLink = @IdI
END
Upvotes: 1
Views: 85
Reputation: 415
I'll suggest to use simple query when possible:
ALTER TRIGGER dbo.trgContractualAmt ON dbo.Vendor
AFTER UPDATE
AS
BEGIN
UPDATE
V
SET
ufAPContAmt += CASE WHEN (V.ufAPCHANGE1AMT <> I.ufAPCHANGE1AMT)
THEN I.ufAPCHANGE1AMT
ELSE 0
END
+ CASE WHEN (V.ufAPCHANGE2AMNT <> I.ufAPCHANGE2AMNT)
THEN I.ufAPCHANGE2AMNT
ELSE 0
END
+ CASE WHEN (V.ufAPCHANGE3AMNT <> I.ufAPCHANGE3AMNT)
THEN I.ufAPCHANGE3AMNT
ELSE 0
END
FROM
Vendor V
INNER JOIN inserted I
ON V.DCLink = I.DCLink;
END;
Upvotes: 1