SQL:设置触发器以限制插入

时间:2014-03-05 20:37:05

标签: sql sql-server

此示例是包含实体CustomerPlanRental的视频租借商店。每个客户都有一个计划,每个计划都有最大租金。我试图强制限制最大数量的视频租赁。我正在使用SQL Server 2012。

以下是我尝试创建触发器:

CREATE TRIGGER maxMovies
ON Rental 
FOR INSERT
AS 
BEGIN
  IF (0 > (SELECT count(*) 
           FROM (SELECT count(*) as total 
                 FROM Inserted i, rental r 
                 WHERE i.customerID = r.customerID) as t, Inserted i, Rental r 
           WHERE t.total > r.max_movies AND i.customerID = r.customerID) )
  BEGIN
    RAISEERROR("maximum rentals surpassed.")
    ROLLBACK TRAN    
  END
END

-- (rest of query)
DROP table...

但是,SQL Server给出了以下错误:

Msg 102, Level 15, State 1, Procedure maxMovies, Line 10
Incorrect syntax near 'RAISEERROR'.
Msg 156, Level 15, State 1, Procedure maxMovies, Line 15
Incorrect syntax near the keyword 'DROP'.

有关如何创建此触发器的任何建议吗?

3 个答案:

答案 0 :(得分:1)

RAISERROR而非RAISEERROR - 这是一个简单的拼写错误。当然,正如Trinimon正确发现的那样,字符串需要用单引号引用,而不是双引号。

RAISERROR('maximum rentals surpassed.')

答案 1 :(得分:1)

使用单引号代替引号...

RAISERROR('maximum rentals surpassed.');

删除一个E并添加冒号;

答案 2 :(得分:0)

CREATE TRIGGER trgI_Rental_VerifyMaxMovies 
ON  dbo.Rental 
FOR INSERT /*, UPDATE*/ -- -- You should also check this limit in the case of UPDATE
AS 
BEGIN
    IF /*UPDATE(CustomerID) AND*/ EXISTS ( -- Uncomment in the case of FOR , UPDATE
        SELECT  * 
        FROM    dbo.[Plan] p INNER JOIN dbo.Rental r ON r.CustomerID = p.CustomerID -- Assumption: "Each customer has a plan"
        WHERE   EXISTS(SELECT * FROM inserted i WHERE i.CustomerID = p.CustomerId)
        GROUP BY p.CustomerID, p.MaxMovies
        HAVING  p.MaxMovies > COUNT(*)
    )
    BEGIN
        ROLLBACK TRAN;
        RAISERROR('maximum rentals surpassed.', 16, 1);    
    END
END