Hi @Shahzaib khan ,
We need the statement like 'update....set... from table inner join inserted' to trigger the row of data which is inserted or updated.
Besides, we could not use 'update a set ... from inserted a' directly without join. Otherwise we would get the error 'The logical tables INSERTED and DELETED cannot be updated'.
In addition, we also need to join packages table since we need the value of VALIDITIY to update the value of Expirydate.
Please try with below statement and check whether it is helpful to you:
CREATE TRIGGER BuyDateUpdate ON UserPackages
AFTER INSERT,UPDATE
as
set nocount on
update a
set BuyDate=GETDATE() , Expirydate = dateadd(dd,C.VALIDITIY,getdate())
from UserPackages A
INNER JOIN inserted B ON A.P_ID=B.P_ID
left join packages C on a.P_ID=C.PID
where A.packagestatus='true'
After I performed one update and insert action, we could have below output.
INSERT INTO UserPackages VALUES (2,1,1,'TRUE',NULL,NULL)
UPDATE UserPackages SET packagestatus='TRUE' WHERE P_ID=2
select * from UserPackages
Output:
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.