循环通过SQL数组

时间:2014-02-11 19:30:46

标签: sql arrays oracle loops stored-procedures

我正在尝试遍历学校列表,如果school_id和关联表中的context_id之间还没有交叉引用,请插入它。

我收到了以下错误:

Erreur(141,3): PL/SQL: SQL Statement ignored
Erreur(141,24): PLS-00321: expression 'IDS' is inappropriate as the left hand side of an assignment statement
Erreur(141,28): PL/SQL: ORA-00904: : invalid identifier
Erreur(143,3): PL/SQL: Statement ignored
Erreur(143,16): PLS-00302: component 'FIRST' must be declared

(以下代码块中的第一行被视为136)

PROCEDURE APPLY_IMPLICITE(P_ID IN TBL_CONTEXTES.ID%TYPE, P_UID IN TBL_ECOLE_CONTEXTES.LAST_UID_MODIFICATION%TYPE)
IS
  TYPE IDS IS TABLE OF TBL_CONTEXTES.ID%TYPE INDEX BY PLS_INTEGER;
  ROW_COUNT NUMBER;
BEGIN
  -- Get the IDs of all the schools
  SELECT ECOLE_ID INTO IDS FROM MV_ECOLES;
  -- Loop through all the schools
  FOR i IN IDS.FIRST..IDS.LAST LOOP
    -- Verify if a row exists
    SELECT COUNT(*) INTO ROW_COUNT FROM TBL_ECOLE_CONTEXTES WHERE ECOLE_ID = IDS(i) AND ID = P_ID;
    -- If no row exist, insert.
    IF ROW_COUNT = 0 THEN
      INSERT INTO TBL_ECOLE_CONTEXTES (ID, ECOLE_ID, LAST_UID_MODIFICATION)
      VALUES (P_ID, IDS(i), P_UID);
    END IF;
  END LOOP;

END APPLY_IMPLICITE;

1 个答案:

答案 0 :(得分:1)

你不应该需要一个循环。您只需插入所有不匹配的行:

查询将看起来某些,如:

INSERT INTO TBL_ECOLE_CONTEXTES
    (ID, ECOLE_ID, LAST_UID_MODIFICATION)
SELECT PID, ECOLE_ID, P_UID 
FROM TBL_ECOLE_CONTEXTES 
WHERE ECOLE_ID NOT IN (SELECT IDS FROM FROM MV_ECOLES WHERE ID = P_ID)

你的表结构并不完全清楚,但这应该是一般的想法。