SQL Server触发器根据表触发更新其他表

时间:2017-01-02 17:40:37

标签: sql sql-server

我是SQL的新手,我想问一个关于触发器的具体问题。我有一个表购买,我想更新其他具有相同ID的表

CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases
AFTER INSERT
AS
BEGIN
    UPDATE EmployeesSalary
    SET MonthlySalesMade = MonthlySalesMade + 1
    WHERE EmployeeID = (SELECT DealMadeByEmployeeID FROM inserted)
END

基于当前插入的行。

但它似乎不起作用(我没有任何错误)。

我的数据库

CREATE DATABASE RealEstateDatabase;
GO

USE RealEstateDatabase;
GO

CREATE TABLE Employees
(
    EmployeeID INT IDENTITY NOT NULL PRIMARY KEY,
    FirstName NVARCHAR(25) NOT NULL,
    SecondName NVARCHAR(25) NOT NULL,
    LastName NVARCHAR(25) NOT NULL,
    NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
    PhoneNumber NVARCHAR(20) NOT NULL,
    Email NVARCHAR(50) NOT NULL,
    [Address] NVARCHAR(50) NOT NULL,

    CONSTRAINT UC_EmployeesNIN UNIQUE (NIN)
);
GO

CREATE TABLE GivingClients -- отдаващи клиенти(наемодатели и продавачи)
(
    ClientID INT IDENTITY NOT NULL PRIMARY KEY,
    ClientType NVARCHAR(20) NOT NULL,--Leaser(наемодател) or Seller
    FirstName NVARCHAR(25) NOT NULL,
    SecondName NVARCHAR(25),
    LastName NVARCHAR(25) NOT NULL,
    NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
    PhoneNumber NVARCHAR(20) NOT NULL,
    Email NVARCHAR(50),
    [Town/Village] NVARCHAR(20),
    [Address] NVARCHAR(50),
    ServedByEmployeeID INT NOT NULL, -- по EmployeeID

    CONSTRAINT FK_GivingClients_Employees 
        FOREIGN KEY (ServedByEmployeeID) REFERENCES Employees(EmployeeID),
    CONSTRAINT CHK_GivingClients CHECK (ClientType IN('наемодател','продавач'))-- наемодател или продавач
);
GO

CREATE TABLE TakingClients -- приемащи клиенти (наематели и купувачи)
(
    ClientID INT IDENTITY NOT NULL PRIMARY KEY,
    ClientType NVARCHAR(20) NOT NULL,
    FirstName NVARCHAR(25) NOT NULL,
    SecondName NVARCHAR(25),
    LastName NVARCHAR(25) NOT NULL,
    NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
    PhoneNumber NVARCHAR(20) NOT NULL,
    Email NVARCHAR(50),
    [Town/Village] NVARCHAR(20),
    [Address] NVARCHAR(50),
    ServedByEmployeeID INT NOT NULL, -- по EmployeeID
    ServedByGivingClientID INT, -- връзка към отдаващите клиенти

    CONSTRAINT FK_TakingClients_Employees 
        FOREIGN KEY (ServedByEmployeeID) REFERENCES Employees(EmployeeID),
    CONSTRAINT FK_TakingClients_GivingClients 
        FOREIGN KEY (ServedByGivingClientID) REFERENCES GivingClients(ClientID),
    CONSTRAINT CHK_TakingClients CHECK (ClientType IN('наемател', 'купувач'))
);
GO

CREATE TABLE EstatesBasicInfo
(
    RealEstateID INT IDENTITY NOT NULL PRIMARY KEY,
    RealEstateType NVARCHAR(20) NOT NULL,--бизнес имот, къща, апартамент, гараж
    Area NVARCHAR(25) NOT NULL,--в квадратни метри
    Architecture NVARCHAR(30), --панел, тухла и т.н.
    Photos IMAGE,
    OfferedByEmployeeID INT NOT NULL,
    [OwnerID] INT NOT NULL,

    CONSTRAINT FK_EstatesBasicInfo_GivingClients 
        FOREIGN KEY ([OwnerID]) REFERENCES GivingClients(ClientID),
    CONSTRAINT FK_EstatesBasicInfo_Employees 
        FOREIGN KEY (OfferedByEmployeeID) REFERENCES Employees(EmployeeID)
);
GO

CREATE TABLE EstatesLocation
(
    RealEstateLocationID INT NOT NULL PRIMARY KEY,
    Country NVARCHAR(50) NOT NULL,
    Region NVARCHAR(50) NOT NULL, --Област
    [Town/Village] NVARCHAR(50) NOT NULL,
    [Address] NVARCHAR(50) NOT NULL,

    CONSTRAINT FK_EstatesLocation_EstatesBasicInfo 
        FOREIGN KEY (RealEstateLocationID) REFERENCES EstatesBasicInfo(RealEstateID)
);
GO

CREATE TABLE EstatesDetails
(
    RealEstateDetailsID INT NOT NULL PRIMARY KEY,
    Position NVARCHAR(11) NOT NULL,--изток, запад, север, юг, югоизток, югозапад, североизток, северозапад
    Conditions NVARCHAR(15) NOT NULL, --добри или лоши
    [Floor] INT NOT NULL, --етажът на който се намира или колко етажа има (в зависимост от видът на обекта)
    Rooms INT NOT NULL,

    CONSTRAINT CHK_EstateDetails CHECK (Position IN('изток', 'запад', 'север', 'юг', 'югоизток', 'югозапад', 'североизток', 'северозапад', 'всички') AND [Floor]>=0 AND Rooms>0),
    CONSTRAINT FK_EstatesDetails_EstatesLocation 
        FOREIGN KEY (RealEstateDetailsID) REFERENCES EstatesLocation(RealEstateLocationID)
);
GO

CREATE TABLE EmployeesSalary
(
    EmployeeID INT NOT NULL PRIMARY KEY,
    CurrentSalary MONEY DEFAULT 0,-- на процент
    MonthlySalesMade INT DEFAULT 0,
    MonthlyRentsMade INT DEFAULT 0,

    CONSTRAINT FK_EmployeesSalary_Employees 
        FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID),
    CONSTRAINT CHK_EmployeesSalary 
        CHECK (CurrentSalary>=0 AND MonthlySalesMade>=0 AND MonthlyRentsMade>=0)
);
GO

CREATE TABLE Purchases
(
    PurchaseID INT IDENTITY NOT NULL PRIMARY KEY,
    DateBought SMALLDATETIME NOT NULL,
    Price MONEY NOT NULL CHECK (Price>0),
    RealEstateID INT UNIQUE NOT NULL,
    DealMadeByEmployeeID INT NOT NULL,

    CONSTRAINT FK_Purchases_EstatesBasicInfo 
        FOREIGN KEY (RealEstateID) REFERENCES EstatesBasicInfo(RealEstateID),
    CONSTRAINT FK_Purchases_Employees 
        FOREIGN KEY (DealMadeByEmployeeID) REFERENCES Employees(EmployeeID)
);
GO

CREATE TABLE Rents
(
    RentID INT IDENTITY NOT NULL PRIMARY KEY,
    StartDate SMALLDATETIME,
    EndDate SMALLDATETIME,
    Price MONEY,
    RealEstateID INT UNIQUE NOT NULL,
    DealMadeByEmployeeID INT NOT NULL,

    CONSTRAINT CHK_Rents CHECK (Price > 0 AND EndDate > StartDate),
    CONSTRAINT FK_Rents_EstatesBasicInfo 
        FOREIGN KEY (RealEstateID) REFERENCES EstatesBasicInfo(RealEstateID),
    CONSTRAINT FK_Rents_Employees 
        FOREIGN KEY (DealMadeByEmployeeID) REFERENCES Employees(EmployeeID)
);

1 个答案:

答案 0 :(得分:0)

您的触发器应适用于单个插入。使用IN

编写更安全
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases AFTER INSERT
AS
BEGIN
    UPDATE EmployeesSalary
    SET MonthlySalesMade = MonthlySalesMade + 1
    WHERE EmployeeID IN (SELECT DealMadeByEmployeeID FROM inserted)
END;

或使用JOIN

CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases AFTER INSERT
AS
BEGIN
    UPDATE es
    SET MonthlySalesMade = es.MonthlySalesMade + 1
    FROM EmployeesSalary es JOIN
         inserted i
         ON es.EmployeeID = i.DealMadeByEmployeeID
END;

注意:如果MonthlySalesMade初始化为NULL而不是0,则表达式应考虑NULL

    SET MonthlySalesMade = COALESCE(es.MonthlySalesMade + 1, 1)