【问题标题】:Oracle insert and replace value with it's primary key value from another tableOracle 用另一个表的主键值插入和替换值
【发布时间】:2020-04-03 20:28:09
【问题描述】:

我有两张桌子。

TABLE2 具有字段 CODE_NM 和DESCRIPTION。 CODE_NM 是此表中的主键和表 TABLE1 中的外键。

表 2:

|---------------------|------------------|
|      CODE_NM        |     DESCRIPTION  |
|---------------------|------------------|
|          001        |description 1 text|
|---------------------|------------------|
|          002        |description 2 text|
|---------------------|------------------|

表 1:

|---------------------|----------------------|------------------|
|      CODE_NM        |  DESCRIPTION_DETAIL  |      USER        |
|---------------------|----------------------|------------------|
|          001        |  some text in here   |      USERID      |
|---------------------|----------------------|------------------|

每次向 TABLE1 插入一行时,用户都会输入 DESCRIPTION、DESCRIPTION_DETAIL 和 USER。对于每个插入,我想用 CODE_NM 替换DESCRIPTION。 可以肯定的是,对于插入的任何说明,都会在 TABLE2 中为其关联的主键创建一个值。

所以我应该可以插入:

INSERT INTO TABLE1 (CODE_NM, DESCRIPTION_DETAIL, USER)
VALUES ('description 1 text','this it the situation','USERID');

而不是“描述 1 文本”,我想显示主键,即“001”:

|---------------------|----------------------|------------------|
|      CODE_NM        |  DESCRIPTION_DETAIL  |      USER        |
|---------------------|----------------------|------------------|
|          001        |  some text in here   |      USERID      |
|---------------------|----------------------|------------------|

这可以使用触发器吗?

【问题讨论】:

    标签: oracle plsql database-trigger


    【解决方案1】:

    您可以为table1 创建这样的插入前触发器:

    SQL> create or replace trigger trg_tbl1_bi
      before insert on table1   
      for each row    
    declare
      begin
         select code_nm
           into :new.code_nm 
           from table2 
          where trim(description) = trim(:new.code_nm);
       exception when no_data_found then 
          raise_application_error(-20001,'No matching record found!');  
      end;  
    end;
    /
    

    但您需要在这些字符串之间完全匹配(table2.description 列和 :new.code_nm of table1 的值)

    【讨论】:

      【解决方案2】:

      您可以创建触发器

      create or replace trigger tbi_table2
      before insert on table2
      on each row
      declare
      begin
        :new.code_nm := select code_nm from table1 where description=:new.code_nm;
      end;
      

      【讨论】:

        【解决方案3】:

        这就是最终的工作:

        create or replace trigger trigger_name
        before insert on TABLE1
        FOR EACH ROW
        DECLARE
           v_code_nm table2.code_nm%type;
        begin
         SELECT code_nm INTO v_code_nm FROM TABLE2 WHERE DESCRIPTION=:new.code_nm;
          :new.code_nm := v_code_nm;
        end;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-25
          • 2023-03-17
          • 2018-07-01
          • 1970-01-01
          • 2018-03-17
          • 1970-01-01
          • 2021-08-05
          • 1970-01-01
          相关资源
          最近更新 更多