【问题标题】:auto populating junction table in oracleoracle中的自动填充连接表
【发布时间】:2017-09-25 02:26:47
【问题描述】:

我的 Oracle Database 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 表中,并检查电话号码。如果没有。存在于客户表中,使用对应的id,否则创建一个新的id。

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

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

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

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

    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。事实上,客户可能拥有多个电话号码。

    【讨论】:

    • 这确实是一个人工练习。客户记录与电话号码一起添加。如果电话没有。不存在才添加新客户,否则为电话号码对应的id。将用于获取地址。我一定会扩展我的模型以包含多个电话号码。非常感谢您的回答。它真的会帮助我学习。
    • 我还想问的另一件事是我可以从excel文件中获取参数到这个过程中吗?如果有什么办法,那就太好了。
    • Excel 很难从头开始,但有办法。请提出一个新问题。
    猜你喜欢
    • 2020-01-06
    • 2011-01-03
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    相关资源
    最近更新 更多