0

我需要创建一个触发器来跟踪电影从 Blockbuster 这样的公司租借的次数。我需要一个单独的触发器来进行插入、删除和更新。

跟踪此租用次数的列称为 num_rentals,其数据类型为 int。此列是包含 *movie_id (pk*)、movie_title、release_year、movie_description 和 num_rentals的Movies表的一部分。customer_rentals表有 item_rental_id(pk)、*movie_id(fk*)、customer_id。

我在这里搜索并找到了一个类似的线程,并尝试使用提供的答案,但无济于事。我执行了以下字符串,没有任何错误,但是当我将数据插入到 Movie 或 Customer_rentals 表中时,我发现 num_rentals 列没有变化。我究竟做错了什么?

CREATE TRIGGER dbo.tr_num_rented_insert ON dbo.customer_rentals
    FOR INSERT
AS
    BEGIN
        UPDATE  m
        SET     num_rentals = num_rentals + 1
        FROM    dbo.movies AS m
                INNER JOIN inserted AS i ON m.movie_id = i.movie_id ;
        END

我稍后将 num_rentals 字段添加到表中,并且我还需要知道如何将当前在 Movies 表中的所有记录的字段值初始化为零。

我想尽可能多地理解这一点,因此非常感谢您的帮助。我读到可能有更有效的方法来管理此类数据,但这是我的导师想要的方式。先感谢您!

4

2 回答 2

0

我怀疑你的问题是 null num_rental 列。因此,您将 null 添加到 1,结果为 null。

就个人而言,我会将 num_rentals 列设置为不可为空,默认为零,但假设您不能这样做,请使用 isnull()。

像这样

alter TRIGGER dbo.tr_num_rented_insert ON dbo.customer_rentals
    FOR INSERT
AS
    BEGIN
        UPDATE  m
        SET     num_rentals = isnull(num_rentals,0) + 1
        FROM    dbo.movies AS m
                INNER JOIN inserted AS i ON m.movie_id = i.movie_id ;
    END

但是,即使这样可行,也有问题;如果您向 customer_rentals 添加多行,它只会增加一。就个人而言,我会更改触发器以解决此问题。

像这样

alter TRIGGER dbo.tr_num_rented_insert ON dbo.customer_rentals
    FOR INSERT
AS
    BEGIN
        UPDATE  m
        SET     num_rentals = isnull(num_rentals,0) + (select COUNT(*) from inserted where movie_id = m.movie_id)
        FROM    dbo.movies AS m
        where   movie_id in (select movie_id from inserted)
    END

就重复信息而言,Aaron 是对的,这是不必要的冗余,根据我的经验,这类事情经常不同步。使用这样一个简单的数据库,num_rentals 列是多余的(为了大方),但是您的电影数据库是一个人为的示例来教您一个概念。基本上,有时您会希望计算值易于访问或过滤。以 SO rep 为例,我假设他们不会在每次显示它时重新计算它。

于 2013-04-20T00:13:44.750 回答
-1

Aaron's frequently upvoted comment suggests that you are doing something unwise. However, since you are doing what your instructor is specifying, I suggest that you look at a couple of things.

First, will your update query work for the initial rental? If the initial value is 0 it will. If the initial value is null it won't.

Second, you might be referencing the wrong table. The trigger is on customer_rentals but your trigger refers to inserted. That strikes me as odd.

Just so you know, I was one of those who upvoted Aaron's comment.

于 2013-04-19T23:05:39.900 回答