簡體   English   中英

SQL Server 2012觸發器

[英]SQL Server 2012 Trigger

我對SQL有一點點小事,這困擾了我一段時間,比如說我有兩個表( CustomerLoan )。 但是,我想要一個基於Borrowertype屬性進行檢查的觸發器。 我之后的第二查詢想,我需要的東西來檢查是否userIDLoans是一樣的一個在Customer ,但必須搞亂起來,不然我完全這種思想的錯誤的方式。

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

您的觸發器必須位於“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM