oracle – 有条件地定义一个Cursor

前端之家收集整理的这篇文章主要介绍了oracle – 有条件地定义一个Cursor前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Oracle中有一个带有varchar2参数的过程.根据该参数的值,我需要定义一个游标.光标将根据参数的值在不同的表上运行.

我想做类似下面的事情,但它在CURSOR定义代码段中抛出一个错误.有任何想法吗?

  1. PROCEDURE GET_RECORDS(v_action IN VARCHAR2)
  2. IS
  3. CURSOR get_records
  4. IS
  5. IF(v_action = 'DO THIS') THEN
  6. SELECT * from <THIS>;
  7. ELSE
  8. SELECT * from <THAT>;
  9. END IF;
  10. BEGIN
  11. OPEN get_records;
  12.  
  13. FETCH get_records
  14. INTO v_thing;
  15.  
  16. v_loop := 0;
  17. WHILE get_records%FOUND
  18. LOOP
  19.  
  20. FETCH get_records
  21. INTO v_thing;
  22.  
  23. END LOOP;
  24. CLOSE get_records;
  25. END;
你需要一个REF CURSOR并打开它,例如:
  1. sql> CREATE OR REPLACE PROCEDURE GET_RECORDS(v_action IN VARCHAR2) IS
  2. 2 v_thing VARCHAR2(10);
  3. 3 get_records SYS_REFCURSOR;
  4. 4 BEGIN
  5. 5 IF (v_action = 'DO THIS') THEN
  6. 6 OPEN get_records FOR
  7. 7 SELECT 1 FROM dual;
  8. 8 ELSE
  9. 9 OPEN get_records FOR
  10. 10 SELECT 2 FROM dual;
  11. 11 END IF;
  12. 12
  13. 13 LOOP
  14. 14 FETCH get_records INTO v_thing;
  15. 15 EXIT WHEN get_records%NOTFOUND;
  16. 16 /* do things */
  17. 17 dbms_output.put_line(v_thing);
  18. 18 END LOOP;
  19. 19 CLOSE get_records;
  20. 20 END;
  21. 21 /
  22.  
  23. Procedure created
  24.  
  25. sql> exec get_records ('DO THIS');
  26. 1
  27.  
  28. PL/sql procedure successfully completed
  29.  
  30. sql> exec get_records ('DO THAT');
  31. 2
  32.  
  33. PL/sql procedure successfully completed

猜你在找的Oracle相关文章