2

我为 SQL 提供了一些输入,我需要获取所有不满足所需条件的 ID 及其计数。

我想知道是否有任何替代使用光标。

DECLARE
   v_count            INTEGER;
   v_output           VARCHAR2 (1000);
   pc                 table1%ROWTYPE;
   unmarked_ids       EXCEPTION;
   dynamic_sql        VARCHAR (5000);
   cur                SYS_REFCURSOR;
   id                 pp.id%TYPE;
   pos                INTEGER;
BEGIN
   v_count := 0;
   SELECT *
     INTO pc
     FROM table1
    WHERE id = '&ID';
   DBMS_OUTPUT.ENABLE;
      dynamic_sql :=
            'SELECT ID from pp
                    WHERE ( TO_CHAR(cdate, ''yyyy/mm/dd'') = 
                    TO_CHAR (:a, ''yyyy/mm/dd''))
                    AND aid IN (SELECT aid FROM ppd WHERE TO_CHAR(cdate, ''yyyy/mm/dd'') = 
                    TO_CHAR (:b, ''yyyy/mm/dd'')
                    AND cid = :c )
                    AND cid <> :d';
      OPEN cur FOR dynamic_sql USING pc.cdate, pc.cdate, pc.id, pc.id;
      LOOP
         FETCH cur INTO id;
         EXIT WHEN cur%NOTFOUND;
         v_count := v_count + 1;
         DBMS_OUTPUT.PUT_LINE (' Id:' || id);
      END LOOP;
      CLOSE cur;
   IF (v_count > 0)
   THEN
      DBMS_OUTPUT.PUT_LINE ( 'Count: ' || v_count || ' SQL: ' || dynamic_sql);
      RAISE unmarked_ids;
   END IF;
   DBMS_OUTPUT.PUT_LINE('SQL ended successfully');
EXCEPTION
   WHEN unmarked_ids
   THEN
      DBMS_OUTPUT.put_line (
         'Found ID's that not marked with the current id.');
   WHEN NO_DATA_FOUND
   THEN
      DBMS_OUTPUT.put_line (
         'No data found in table1 with the current id ' || '&ID');
END;

查询中有绑定变量。其中一个是日期,还有三个。需要显示计数和 ID,稍后将报告。

4

1 回答 1

1

您可以将 rowid 与索引值 (0...n) 一起存储在临时表中,然后使用 while 循环遍历索引值并使用 rowid 连接到真实表。

于 2012-08-06T17:09:30.340 回答