I am new in SQL, can anybody please help me to fix the trigger bellow.
I have these 2 tables(Review and Offer), I would like to update Review table ON Insert, Update and
Try the code below; hopefully it does what you're after; the logic's not exactly the same, but I've tried to guess what you're aiming for and code that:
CREATE TRIGGER dbo.InserUpdateReview
ON dbo.Review
FOR INSERT, UPDATE, DELETE
AS
BEGIN
--if it's an update
if exists (select top 1 1 from inserted i inner join deleted d on d.ReviewId = i.ReviewId)
begin
--update the review table
UPDATE a
SET a.OfferId = max(b.OfferId)
, a.CustomerId = max(b.CustomerId)
FROM dbo.Review a
INNER JOIN Inserted i
ON a.ReviewId = i.ReviewId
AND a.OfferId IS NULL
AND a.CustomerId IS NULL
LEFT OUTER JOIN dbo.Offer b
ON b.UserKey = a.UserKey
AND b.ASIN = a.ASiN
AND b.ReviewId IS NULL
--and the corresponding orders table
UPDATE o
SET o.ReviewId = max(r.ReviewId)
, o.ReviewDate = getDate()
FROM dbo.Offer o
INNER JOIN Inserted ins
ON o.UserKey = ins.UserKey
AND o.ASIN = ins.ASIN
AND o.ReviewId IS NULL
LEFT OUTER JOIN dbo.Review r
ON r.UserKey = o.UserKey
AND r.ASIN = o.ASiN
AND r.ReviewId = ins.ReviewId
end
END
NB: If you can explain your aim with this logic we may be better able to advise.