I’m trying to create a fairly simple trigger that would add one to a column that keeps track of the number of rentals from a movie distribution company similar to Netflix.
The columns I am focused on are:
- Movies (
movie_id, movie_title, release_year, num_rentals) - Customer_rentals (
item_rental_id, movie_id, rental_date_out, rental_date_returned)
My current trigger looks like this:
CREATE TRIGGER tr_num_rented_insert
ON customer_rentals FOR INSERT
AS
BEGIN
UPDATE movies
SET num_rentals=num_rentals+1
WHERE customer_rentals.movie_id=movies.movie_id;
END;
It returns the error:
Msg 4104, Level 16, State 1, Procedure tr_num_rented_insert, Line 7
The multi-part identifier “customer_rentals.movie_id” could not be
bound.
I just want it to match the movie_id’s and add 1 to the number of rentals.
You need to join to the
insertedpseudo-table:But I have to ask, what is the point of keeping this count up to date in the movies table? You can always get the count in a query instead of storing it redundantly:
And if performance of that query becomes an issue, you can create an indexed view to maintain the count so that you don’t have to keep it up to date with a trigger:
This causes the same kind of maintenance as your trigger, but does it without your trigger, and does it without affecting the
moviestable. Now to get the rental counts you can just say:(We use a LEFT JOIN here because a movie may not have been rented yet.)
An additional bonus here is that you don’t have to perform any tricks to get other columns from the movies table into the result. It also ensures that the data is accurate even if a rental is deleted (your trigger will continue to happily add +1 to the count).