简体   繁体   中英

Oracle procedure insert into table from another table

I have this code from trigger and now i need to create procedure because i cant use trigger.

CREATE OR REPLACE TRIGGER LIVE_MATCHES_TO_MATCHES 
    instead of insert ON LIVE_MATCHES
   for each row
declare
   p_priority number:= 1;
   p_sport number:=0;
   begin
     insert into matches(sub_list , priority , sport, created) 

     select :new.comp_name , p_priority, p_sport,sysdate
     from dual
      where not exists (      
     select 1 from matches
    where sub_list = :new.comp_name);

   end;

this is procedure :

CREATE OR REPLACE PROCEDURE LIVE_MATCHES_SOCCER_T IS 
       p_priority number := 1;
   p_sport number:=0;   
begin
INSERT INTO matches("sub_list","priority","sport","created")
SELECT LIVE_MATCHES.COMP_NAME,p_priority,p_sport, sysdate
FROM  LIVE_MATCHES WHERE LIVE_MATCHES.COMP_NAME <> matches.SUB_LIST;
commit;
end;

but I m getting error that matches.sub_list is invalid identifier. How will i create procedure that will insert into table only if sub_list is different from comp_name.. I will set up job that will call this procedure every 5 minutes..

I think you want:

INSERT INTO matches("sub_list","priority","sport","created")
    SELECT lm.COMP_NAME, lm.p_priority, lm.p_sport, sysdate
    FROM LIVE_MATCHES lm 
    WHERE NOT EXISTS (SELECT 1
                      FROM matches m
                      WHERE lm.COMP_NAME <> m.SUB_LIST
                     );

Unless your column names are lower-case (which can only be done in Oracle by using quotes when you create them - and which is not a particularly good idea in any case), then your stored procedure won't work, as you're quoting lower-case identifiers in it. Try this instead:

CREATE OR REPLACE PROCEDURE LIVE_MATCHES_SOCCER_T IS 
   p_priority number := 1;
   p_sport number := 0;   
begin
    INSERT INTO matches
      ( sub_list, priority, sport, created )
    SELECT LIVE_MATCHES.COMP_NAME, p_priority, p_sport, sysdate
      FROM live_matches
     WHERE NOT EXISTS ( SELECT 1 FROM matches WHERE LIVE_MATCHES.COMP_NAME = matches.SUB_LIST );
    commit;
  end;

You can use MERGE statement

CREATE OR REPLACE
PROCEDURE PR_INSRT_INTO_MATCHES
IS
  P_PRIORITY NUMBER := 1;
  P_SPORT    NUMBER := 0;
BEGIN
  MERGE INTO MATCHES M USING
  (SELECT DISTINCT COMP_NAME AS COMP_NAME FROM LIVE_MATCHES
  ) LM ON (LM.COMP_NAME=M.SUB_LIST)
WHEN NOT MATCHED THEN
  INSERT
    (
      M.SUB_LIST,
      M.PRIORITY,
      M.SPORT,
      M.CREATED
    )
    VALUES
    (
      LM.COMP_NAME,
      P_PRIORITY,
      P_SPORT,
      SYSDATE
    )
    COMMIT;
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM