tags:

views:

586

answers:

1

I got two tables Product(Productname VARCHAR(10), Rating REAL) and Review(RatingID INT, Productname VARCHAR(10), Rating INT). The Rating of the product is the average of all Ratings given in reviews for that specifig product.
I'd like to have a trigger, that updates a product whenever a new review is inserted or update, but I just can't wrap my head around how to do it. Is there some db2 equivalent to inserted() from SQL Server?

My apologies for the weak question.

+2  A: 

DB2 After Insert trigger:

CREATE TRIGGER NEW_REVIEW
 AFTER INSERT ON REVIEW
  REFERENCING NEW AS N_ROW
   FOR EACH ROW
    UPDATE PRODUCT SET Rating = (
      Select AVG(Rating) 
      from Review 
      where ProductName = N_ROW.ProductName
      )

After Update:

CREATE TRIGGER NEW_REVIEW
 AFTER UPDATE ON REVIEW
  REFERENCING NEW AS N_ROW
   FOR EACH ROW
    UPDATE PRODUCT SET Rating = (
      Select AVG(Rating) 
      from Review 
      where ProductName = N_ROW.ProductName
      )

After Delete:

CREATE TRIGGER NEW_REVIEW
 AFTER DELETE ON REVIEW
  REFERENCING OLD AS O_ROW
   FOR EACH ROW
    UPDATE PRODUCT SET Rating = (
      Select AVG(Rating) 
      from Review 
      where ProductName = O_ROW.ProductName
      )

Check out CREATE TRIGGER statement for additional info.

Rashmi Pandit
Thank you.Not entirely correct though. The WHERE Clause for the UPDATE is missing.
pmr
Oops! I didn't check the Q properly. You also need an update trigger. I'll post it too.
Rashmi Pandit
That's IMHO actually one of the few perfectly valid use cases for a trigger :-)
Steve Schnepp