oracle 带-1参数的光标

gab6jxml  于 2022-12-18  发布在  Oracle
关注(0)|答案(2)|浏览(101)

我一直在尝试使用带参数的游标查询雇员,但是我想检索所有数据而不向参数传递值,有什么想法吗?

DECLARE

   cursor emp_cursor(v_dept_id number) IS
    SELECT * FROM employees
    WHERE department_id = v_dept_id;
    
    
BEGIN 
    FOR emp_record IN emp_cursor(60) LOOP
        dbms_output.put_line(' id = ' || emp_record.employee_id);
    END LOOP;
END;
slsn1g29

slsn1g291#

如果使用-1表示想要所有值,则可以用途:

DECLARE
  cursor emp_cursor(v_dept_id number) IS
    SELECT * FROM employees
    WHERE department_id = v_dept_id
    OR    v_dept_id = -1;
BEGIN 
  FOR emp_record IN emp_cursor(-1) LOOP
    dbms_output.put_line(' id = ' || emp_record.employee_id);
  END LOOP;
END;
/

然后,对于样本数据:

CREATE TABLE employees (employee_id, department_id) AS
SELECT 1, 1 FROM DUAL UNION ALL
SELECT 2, 1 FROM DUAL UNION ALL
SELECT 3, 1 FROM DUAL UNION ALL
SELECT 4, 2 FROM DUAL UNION ALL
SELECT 5, 2 FROM DUAL UNION ALL
SELECT 6, 2 FROM DUAL;

输出:

id = 1
 id = 2
 id = 3
 id = 4
 id = 5
 id = 6


fiddle

watbbzwu

watbbzwu2#

你的代码没问题--只需要像下面这样修改where子句。它涵盖了传递v_dept_id的所有选项--如果它为Null或-1,你将得到所有记录--否则只会得到传递到游标的department:

SET SERVEROUTPUT ON
DECLARE
    CURSOR emp_cursor(v_dept_id NUMBER) IS
    SELECT * FROM emp
--  below is the where clause handling all of the options
    WHERE DEPTNO = CASE Nvl(v_dept_id, -1) WHEN -1 THEN DEPTNO ELSE v_dept_id END;
BEGIN 
    FOR emp_record IN emp_cursor(10) LOOP
        dbms_output.put_line(' id = ' || emp_record.empno);
    END LOOP;
END;

通过值的结果:
| emp_cursor(空)或(-1)|emp_光标(10)|
| - ------|- ------|
| 编号= 7939|编号= 7939|
| 编号= 7369|编号= 7369|
| 编号= 7499|编号= 7782|
| 编号= 7521|编号= 7839|
| 编号= 7566|编号= 7902|
| 编号= 7654|编号= 7934|
| 编号= 7698||
| 编号= 7782||
| 编号= 7788||
| 编号= 7839||
| 编号= 7844||
| 编号= 7876||
| 编号= 7900||
| 编号= 7902||
| 编号= 7934||
注意:旧的emp表在这里-调整它到您的

相关问题