oracle 如何将ID名称作为外键插入到过程中,以使空值不在输出中

pdtvr36n  于 2023-01-20  发布在  Oracle
关注(0)|答案(2)|浏览(119)

NAME_ID列是NULL,表table13_prc中的NAME_ID是外键,表table_prc4中的ID是主键。我想在NAME_ID列中输出来自table_prc4的id的令牌。
我的代码是:

Create Table table13_prc (
                          Family    VARCHAR2(200),
                          Name      VARCHAR2(200) ,
                          ID        INTEGER  NOT NULL PRIMARY KEY ,
                          NAME_ID   INTEGER  REFERENCES TABLE_PRC4(id)
                          ) ;
                                                   
CREATE SEQUENCE ID_seq5
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1 ;
   
Create or Replace trigger trg5 
  BEFORE insert on  table13_prc 
   for each row 
   BEGIN
   select ID_seq5.nextval INTO :new.ID from dual ;
   END ;
 
CREATE OR REPLACE PROCEDURE addnewmem6 (str IN VARCHAR2)
   AS
    BEGIN
      INSERT INTO table13_prc (Name, Family)
          WITH
            temp
             AS
               (    SELECT REGEXP_SUBSTR (str,
                                           '[^,]+',
                                          1,
                                        LEVEL) val
                    FROM DUAL
               CONNECT BY LEVEL <= REGEXP_COUNT (str, ',') + 1)
         SELECT TRIM(SUBSTR(val, 1, INSTR (val, ';') - 1)),
               TRIM(SUBSTR(val, INSTR (val, ';') + 1))
          FROM temp;
 
      COMMIT;
   END;
 
CREATE OR REPLACE PROCEDURE delete_member2 (par_id IN VARCHAR2)
IS
BEGIN
   DELETE FROM table13_prc
         WHERE id = par_id;
END;

BEGIN
  addnewmem6 ('faezeh;Ghanbarian,pari;izadi');
END;
    
BEGIN
  addnewmem6 ('Saeed;Izadi,Saman; Rostami');
END; 
    
BEGIN
  delete_member2 (1);
END;
 
BEGIN
  delete_member2 (2) ;
END;
 
CALL delete_member2(5);
 
CALL delete_member2(66);

   
select *
from  table13_prc ;

我想在输出中,列NAME_ID不是null,我想在NAME_ID中取table_prc4中的id。

9jyewag0

9jyewag01#

我希望在输出中,列NAME_ID不为空,我希望在NAME_ID中采用table_prc4中的表单ID。
您不能“自动化”它。table13_prc.NAME_ID引用table_prc4.ID,但是INSERT语句不知道使用 * 哪个 * table_prc4.ID值。应该由您指定该值。
外键约束不允许您插入table_prc4.ID中不存在的值(到table13_prc.NAME_ID中)。

idfiyjo8

idfiyjo82#

您需要从table_prc4中查找正确的name_id:

INSERT INTO table13_prc (Name, Family, Name_ID)
      WITH
        temp
         AS
           (    SELECT REGEXP_SUBSTR (str,
                                       '[^,]+',
                                      1,
                                    LEVEL) val
                FROM DUAL
           CONNECT BY LEVEL <= REGEXP_COUNT (str, ',') + 1)
     SELECT TRIM(SUBSTR(val, 1, INSTR (val, ';') - 1)),
           TRIM(SUBSTR(val, INSTR (val, ';') + 1)),
           table_prc4.id
      FROM temp,
           table_prc4
     WHERE temp.TRIM(SUBSTR(val, 1, INSTR (val, ';') - 1)) = table_prc4.name ???

你也可以在你的insert触发器中这样做,但是无论是在你的insert语句中还是在你的insert触发器中,你都必须以某种方式查找ID值,而Oracle不会为你这样做。

相关问题