如何选择使用触发器插入的列?

时间:2016-05-19 18:39:43

标签: sql oracle plsql triggers

我创建了以下表格:

env.readTextFile(path_to_files).first(10).print()

我插入了以下数据:

create table people (
        ID              varchar2(9),
        name            varchar2(20),
        CONSTRAINT pk_ID PRIMARY KEY (ID)
);

 create table cars (
        license_plate   varchar2(9),
        ID              varchar2(9),
        CONSTRAINT pk_license_plate PRIMARY KEY (license_plate)
);

create table accidents (
        code          varchar2(9),
        license_plate varchar2(9),    
        CONSTRAINT pk_code PRIMARY KEY (code)
);

问题是:如何触发添加新车后,Oracle会显示一条消息类型:“X客户端购买了车牌为Y的车”。 ?

例如,我插入了以下数据:

insert into people(ID, name) values('0x1','Louis');
insert into people(ID, name) values('0x2','Alice');
insert into people(ID, name) values('0x3','Peter');

insert into cars(license_plate, ID) values('001','0x1');
insert into cars(license_plate, ID) values('002','0x2');
insert into cars(license_plate, ID) values('003','0x1');
insert into cars(license_plate, ID) values('004','0x3');

insert into accidents(code, license_plate) values('fd1','001');
insert into accidents(code, license_plate) values('fd2','004');
insert into accidents(code, license_plate) values('fd3','002');

甲骨文:

  

“客户”路易斯“买了车牌为005”的车。

我尝试过以下触发器:

insert into cars(license_plate, ID) values('005','0x1');

1 个答案:

答案 0 :(得分:2)

你的触发器没有名字;你在打开光标之后但是在获取之前产生输出,所以没有当前行;并且您的光标正在尝试查询触发器所针对的表,这将导致变异表错误。您的输出中还需要一些空格。

您不需要查看cars表,因为您拥有new伪记录中所需的所有数据。

create or replace trigger cars_ai_trig
after insert on cars
for each row
declare
  cursor c_trigger is
    select p.name 
    from people p
    where p.ID = :new.ID;
  v_trigger c_trigger%rowtype;
begin
  open c_trigger;
  fetch c_trigger into v_trigger;
  dbms_output.put_line('The client ' || v_trigger.name || ' has bought the car whose license plate is ' || :new.license_plate);
  close c_trigger;
end trigger;
/

Trigger CARS_AI_TRIG compiled

set serveroutput on
insert into cars(license_plate, ID) values('005','0x1');

1 row inserted.
The client Louis has bought the car whose license plate is 005

这里你真的不需要光标,你可以有一个简单的标量变量并直接选择它:

create or replace trigger cars_ai_trig
after insert on cars
for each row
declare
  v_name people.name%type;
begin
  select p.name
  into v_name
  from people p
  where p.id = :new.id;

  dbms_output.put_line('The client ' || v_name || ' has bought the car whose license plate is ' || :new.license_plate);
end trigger;
/

我还考虑将列名'ID'更改为更具描述性的内容;在cars表中,它不是一个人ID。您也应该对其进行外键约束,并在accidents.license_plate上。如果没有该FK关系,您可以在cars中插入一个people中不存在的ID;在这种情况下,触发器将获得无数据发现的异常。