在oracle中自动填充连接表

时间:2017-04-27 10:34:14

标签: oracle plsql

我的 Oracle数据库11g 中有3个表:

CREATE TABLE Customer (
  cust_id    NUMBER PRIMARY KEY,
  cust_name  VARCHAR2(100),
  cust_phone VARCHAR2(20)
);

CREATE TABLE Address (
  address_id NUMBER PRIMARY KEY,
  address    VARCHAR2(500),
  area       VARCHAR2(100)
);

CREATE TABLE Customer_Address (
  cust_id    NUMBER REFERENCES Customer ( cust_id ),
  Address_id NUMBER REFERENCES Address ( address_id ),
  PRIMARY KEY ( cust_id, address_id )
);

现在我想自动将id输入到Customer_Address表中的过程检查电话号码。如果没有。存在于customer表中,使用相应的id else创建一个新的id。

我通过创建一个视图来尝试此操作,其中我插入了客户和地址表的ID,然后使用而不是插入触发器来填充联结表,但它不起作用。

这可以使用序列和触发器来完成吗?或任何其他方式?请帮帮我

1 个答案:

答案 0 :(得分:0)

如果你要在数据库中实现业务逻辑(事实上你应该这样做),正确的方法是使用存储过程而不是触发器。

create or replace procedure insert_address
   ( p_phone_number in customer.cust_phone%type
     , p_address in address.address%type
     , p_area in address.area%type )
is
    l_cust_id customer.cust_id%type;
    l_addr_id address.address_id%type;
begin
    begin
        select c.cust_id 
        into l_cust_id
        from  customer c
        where c.cust_phone = p_cust_phone;
    exception
        when no_data_found then
             insert into customer
             values (customer_id_seq.nextval, 'No name', p_cust_phone) 
             returning cust_id  into l_cust_id;
    end;
    insert into address
    values (address_id_seq.nextval, p_address, p_area) 
    returning address_id  into l_addr_id;
    insert into customer_address
    values (l_cust_id, l_addr_id);
end;

异常处理和其他细节留给读者练习。

说实话,这是一项人为的练习:IRL客户记录应该在收集地址之前存在。在该方案中,新客户记录不包括客户名称 - 一个相当重要的属性。即使在这个移动电话时代,电话号码也不太可能代理客户的UID。事实上,客户可能拥有多个电话号码。

相关问题