Use Homework250417
Go
CREATE TABLE Employee(
    EmployeeID INT PRIMARY KEY,
    Name NVARCHAR(20),
    Age INT,
    Salary INT,
);
Go
/* 删除员工表信息时，如果员工个数<5，不允许删除员工信息，
   记录下企图删除员工信息的行为 */
CREATE TABLE DelEmployeeAttempt(
    AttemptID INT PRIMARY KEY IDENTITY(1,1),
    EmployeeID INT,
    AttemptTime DATETIME DEFAULT GETDATE(),
);
Go
CREATE TRIGGER trg_DelEmployee
ON Employee
INSTEAD OF DELETE
AS
BEGIN
    DECLARE @EmployeeCount INT;
    SELECT @EmployeeCount = COUNT(*) FROM Employee;
    IF @EmployeeCount < 5
    BEGIN
        INSERT INTO DelEmployeeAttempt (EmployeeID)
        SELECT EmployeeID FROM DELETED;
        RAISERROR(N'少于5名员工，无法删除', 16, 1);
    END
    ELSE
    BEGIN
        DELETE FROM Employee WHERE EmployeeID IN (SELECT EmployeeID FROM DELETED);
        PRINT(N'删除员工信息成功');
    END
END;
Go