2015-02-23 169 views
0

我有一個小問題,現在一直困擾着我的SQL,比方說我有兩個表(CustomerLoan)。不過,我想要一個基於Borrowertype屬性進行檢查的觸發器。我想在第二個查詢之後,我需要檢查Loans中的userID是否與Customer中的userID相同,但是必須將其搞亂,否則我完全錯誤地認爲這是錯誤的。SQL Server 2012觸發器

CREATE TABLE Customer 
(
    userID int identity primary key, 
    Name varchar(20), 
    Borrowertype varchar(20) 
); 

CREATE TABLE Loan 
(
    Id int identity primary key, 
    userID int, 
    FOREIGN KEY (userID) REFERENCES Customer(userID) 
); 

IF OBJECT_ID ('Customer.maximum_books_per_user','TR') IS NOT NULL 
    DROP TRIGGER Customer.maximum_books_per_user; 
GO 

CREATE TRIGGER maximum_books_per_user ON Customer 
AFTER INSERT 
AS 
IF (SELECT Borrowertype FROM Customer) = 'diffborrowertypehere' 
    AND (SELECT COUNT(*) FROM inserted AS i JOIN Customer AS c 
     ON ??? WHERE ??? 
     ) > 5 
BEGIN 
    ROLLBACK TRANSACTION 
    RAISERROR('You have reached maximum allowed loans.', 16, 1) 
END 
GO 
+0

插入的只包含插入與此一個交易行處理多個客戶插入。你應該只檢查一下還是對早期的貸款呢?也許檢查約束+一個函數會更容易弄清楚。 – 2015-02-23 19:48:22

+0

您的'SELECT BorrowerType FROM Customer'將返回來自Customer的所有行,因此您無法使用簡單的'=',因爲這沒有意義。你能否解釋你對觸發器的要求,因爲從目前爲止發佈的內容不清楚嗎? – TobyLL 2015-02-23 19:48:54

+0

@TobbyLL嗯...我想檢查貸款中可以有的最大行數。所以如果一個人超過5個,那麼它就不會被插入到貸款中。 – zxcvsadfqwerty 2015-02-23 19:52:29

回答

2

您的觸發器需要放在Loan表中,因爲這是插入的行可能被拒絕的地方。事情是這樣的:

編輯:重寫一次

CREATE TRIGGER maximum_books_per_user ON Loan 
FOR INSERT 
AS 
-- Fail if there are any customers that will have more than the maximum number of loans 
IF EXISTS (
    SELECT i.userID, COUNT(*) 
    FROM inserted i 
    JOIN Loan l 
     ON i.userID = l.userID 
    GROUP BY i.userID 
    HAVING COUNT(*) >= 5 
) 
BEGIN 
    ROLLBACK TRANSACTION 
    RAISERROR('You have reached maximum allowed loans.', 16, 1) 
END 
+0

啊,是的,我想這是有道理的! – zxcvsadfqwerty 2015-02-23 20:04:24

+0

爲多個客戶的插入重寫觸發器 – TobyLL 2015-02-23 20:12:11