触发不为参与事故的驾驶员创建保险单的触发器

时间:2019-04-14 23:35:09

标签: sql oracle triggers

你好,我是SQL触发器的新手,并且需要一些帮助。我正在处理3张涉及驾驶员,交通事故和保险单的表格。我正在尝试创建一个触发器,该触发器将不允许为发生事故的驾驶员制定保险单。

这是我到目前为止尝试过的:

CREATE TABLE insurance_policy(
    id INT,
    ssn_driver INT,
    expiration_date DATE,
    PRIMARY KEY (id)
);

CREATE TABLE accident(
    id INT,
    ssn_driver INT,
    accident_date DATE,
    details VARCHAR2(64),
    PRIMARY KEY (id),
    FOREIGN KEY (id) REFERENCES insurance_policy,
    FOREIGN KEY (ssn_driver) REFERENCES driver
);

CREATE TABLE driver(
    ssn_driver INT,
    name VARCHAR2(64),
    age INT CHECK (age>15),
    PRIMARY KEY(ssn_driver)
);

CREATE TRIGGER no_insurance_policy
    AFTER INSERT OR UPDATE ON insurance_policy
    FOR EACH ROW 
    BEGIN 
        IF EXISTS (select ssn_driver FROM Inserted INNER JOIN accident)
        BEGIN
            rollback transaction
            raiserror ('some message', 16, 1)
        END
    END

这不能编译,但是我对如何从这里继续感到困惑。有人可以帮助我创建触发器吗?

编辑:这是错误

Error starting at line : 31 in command -
    BEGIN 
        IF EXISTS (select ssn_driver FROM Inserted INNER JOIN accident)
        BEGIN
            rollback transaction
            raiserror ('some message', 16, 1)
        END
    END
Error report -
ORA-06550: line 2, column 58:
PLS-00103: Encountered the symbol "JOIN" when expecting one of the following:

   ) , with group having intersect minus start union where
   connect
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

1 个答案:

答案 0 :(得分:3)

首先,您需要插入BEFORE而不是AFTER。然后,您的语法甚至不是Oracle。这大约是您需要做的。我还没有测试。

CREATE TRIGGER no_insurance_policy
    BEFORE INSERT OR UPDATE ON insurance_policy
    FOR EACH ROW 
DECLARE
    v_accidentCout NUMBER(10);
BEGIN
    Select Count(*) Into v_accidentCout 
    From accident
    Where ssn_driver = old.ssn_driver;

    If v_accidentCout > 0 Then
        raise_application_error(-12345, 'Driver has accidents');
    End If;  
END;
/

我会将commit / rollback留给调用insert / update的块。