更新后触发SQL

时间:2016-11-20 20:43:01

标签: sql-server tsql triggers

我目前正在上大学,并且在课堂上完成了这个问题。我花了很多时间试图用一半的课程来淘汰它,每次我们认为我们已经接近搞清楚时,我们意识到我们没有什么值得保留的。所以我们从第一个方向开始,这就是我们现在所处的位置。我提供了问题和问题的错误。任何帮助都是极好的。这是我们第一次使用触发器,所以我们并不真正理解。换句话说,最基本的答案,或者有很多解释都会非常有用。 ([QuestionPic] [1])([ERD Pic] [2])

第一个例子

ALTER TRIGGER [TRG_MEM_BALANCE]
    ON [DETAILRENTAL]
    AFTER UPDATE
AS
BEGIN

    DECLARE @PRIOR_LATEFEE DECIMAL (5,2);
    DECLARE @NEW_LATEFEE DECIMAL (5,2);
    DECLARE @RENT_FEE INT


    IF(EXISTS (SELECT * FROM deleted) AND EXISTS(SELECT * FROM inserted))
    BEGIN
        DECLARE MOVIE_CURSOR CURSOR FOR 
        SELECT I.Rent_Num, SUM(@NEW_LATEFEE - @PRIOR_LATEFEE)
        FROM deleted D INNER JOIN inserted I ON I.Rent_Num = D.Rent_Num AND I.Vid_Num = D.Vid_Num
        WHERE (@NEW_LATEFEE > 0) OR (@NEW_LATEFEE IS NOT NULL)
        GROUP BY I.Rent_Num

        OPEN MOVIE_CURSOR
        FETCH NEXT FROM MOVIE_CURSOR 
                        INTO @RENT_FEE, @NEW_LATEFEE

        WHILE (@@FETCH_STATUS = 0)
            BEGIN
                UPDATE MEMBERSHIP
                SET Mem_Balance = @NEW_LATEFEE + @PRIOR_LATEFEE
                WHERE Mem_Num = (SELECT Mem_Num FROM RENTAL WHERE Rent_Num = @RENT_FEE)
                FETCH NEXT FROM MOVIE_CURSOR 
                                INTO @RENT_FEE, @NEW_LATEFEE 
                END

            CLOSE MOVIE_CURSOR
            DEALLOCATE MOVIE_CURSOR
    END
END

第二个例子

ALTER TRIGGER [TRG_MEM_BALANCE]
   ON  [DETAILRENTAL]
   AFTER UPDATE

AS
BEGIN

    DECLARE @LATE_FEE DECIMAL(5,2)
    DECLARE @NEW_MEM_BALANCE DECIMAL(5,2)



    IF(EXISTS (SELECT * FROM DELETED) AND EXISTS(SELECT * FROM INSERTED))
    BEGIN
        DECLARE MOVIECURSOR CURSOR FOR
        SELECT M.MEM_NUM, M.MEM_FNAME, M.MEM_LNAME, M.MEM_BALANCE
        FROM DETAILRENTAL D INNER JOIN RENTAL R ON R.RENT_NUM = D.RENT_NUM
        INNER JOIN MEMBERSHIP M ON R.MEM_NUM = M.MEM_NUM
        GROUP BY M.MEM_NUM, M.MEM_FNAME, M.MEM_LNAME, M.MEM_BALANCE

        OPEN MOVIECURSOR
        FETCH NEXT FROM MOVIECURSOR

        WHILE @@FETCH_STATUS = 0
        BEGIN
            UPDATE DETAILRENTAL
            SET @LATE_FEE = DATEDIFF(DAY, DETAIL_RETURNDATE, DETAIL_DUEDATE)* DETAIL_DAILYLATEFEE
            WHERE DETAIL_DAILYLATEFEE = @LATE_FEE
            FETCH NEXT FROM MOVIECURSOR

            UPDATE MEMBERSHIP
            SET @NEW_MEM_BALANCE = MEM_BALANCE + @LATE_FEE
            FETCH NEXT FROM MOVIECURSOR

            END
            CLOSE MOVIECURSOR
            DEALLOCATE MOVIECURSOR

    END
END

我无法弄清楚如何在代码框中完成所有操作。

0 个答案:

没有答案