SQL代替插入触发器

时间:2019-12-04 12:38:02

标签: mysql

我有这些表:

Aircraft(acID, acNAME, range)  
Employee(empID, empNAME, salary)  
Certification(empID, acID)  

此视图:

CREATE VIEW AircraftPilot AS
SELECT empNAME, salary, acNAME, range
FROM Employee e, Certification c, Aircraft a
WHERE c.empID = e.empID AND c.acID=a.acID;

我必须创建一个而不是触发器来插入,像这样:

INSERT INTO AircraftPilot (empNAME, salary, acNAME, range) VALUES ('John', '3000', 'BOEING 737', '4500')

1 个答案:

答案 0 :(得分:0)

CREATE TRIGGER tr_AircraftPilot 
ON AircraftPilot
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO Aircraft (acNAME, range)
    SELECT
        i.acNAME, i.range
    FROM
        inserted i;
    Declare @acID as int = (SELECT SCOPE_IDENTITY());

    INSERT INTO Employee (empNAME, salary)
    SELECT
        i.empNAME, i.salary
    FROM
        inserted i
    Declare @empId as int = (SELECT SCOPE_IDENTITY());

    INSERT INTO Certification (empID, acID)
    SELECT @empId, @acID
END

注意::提供的解决方案适用于Microsoft SQL Server。正如您没有提到DBMS产品名称一样,我不知道这是否对您有帮助。 谢谢