oracle 语句Select * From Table Where Cursor -如何循环此游标?

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

我创建了一个变量IDS TABLECLIENT.ID&type;,并使用以下内容填充该变量:

OPEN V_ID;
   LOOP
    FETCH V_ID INTO IDS;
    EXIT WHEN V_ID%NOTFOUND;
   END LOOP; 
 CLOSE V_ID;

它存储了5个id客户端,但是当我在select语句中使用它时,我等待了5个寄存器,但是我只得到了1:

SELECT * 
  FROM TABLECLIENT
 WHERE ID IN IDS;

也许我必须在语句中循环id?请帮助oracle的朋友

js4nwp54

js4nwp541#

IDS-在某一时刻-只包含游标读取的一行。
例如,这是Scott示例模式中的部门表:

SQL> select * from dept;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

这段代码模拟了你所拥有的(尽管,如果你发布了这些信息会更好);游标选择部门编号,然后在另一个查询中使用该值。

SQL> set serveroutput on
SQL> declare
  2    cursor v_id is select deptno from dept;
  3    ids    dept.deptno%type;
  4    l_cnt  number;
  5  begin
  6    open v_id;
  7    loop
  8      fetch v_id into ids;
  9      exit when v_id%notfound;
 10
 11      -- display IDS's contents:
 12      dbms_output.put_line('Department ' || ids);
 13
 14      -- you can do "something" with that value; for example,
 15      -- count employees who work in that department
 16      select count(*)
 17        into l_cnt
 18        from emp
 19        where deptno = ids;
 20      dbms_output.put_line('...Number of employees in DEPT ' || ids ||
 21                           ' = ' || l_cnt);
 22    end loop;
 23    close v_id;
 24  end;
 25  /

结果为:

Department 10                           --> this is value fetched in the 1st loop round
...Number of employees in DEPT 10 = 3
Department 20                           --> fetched in the 2nd round
...Number of employees in DEPT 20 = 5
Department 30
...Number of employees in DEPT 30 = 6
Department 40
...Number of employees in DEPT 40 = 0

PL/SQL procedure successfully completed.

SQL>

相关问题