Oracle程序从另一个表插入表中

时间:2018-04-23 11:17:32

标签: sql oracle plsql insert

我从触发器获取此代码,现在我需要创建过程,因为我无法使用触发器。

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;

这是程序:

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;

但是我收到匹配.sub_list是无效标识符的错误。 如果sub_list与comp_name不同,我将如何创建将插入到表中的过程..我将设置每5分钟调用此过程的作业..

3 个答案:

答案 0 :(得分:0)

我想你想要:

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
                     );

答案 1 :(得分:0)

除非你的列名是小写的(这只能在你创建它们时使用引号在Oracle中完成 - 而且在任何情况下都不是特别好的主意),那么你的存储过程将不起作用,如你在其中引用小写标识符。试试这个:

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;

答案 2 :(得分:0)

您可以使用MERGE语句

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;