Oracle函数,如何将参数传递给游标并使用它

时间:2017-11-23 12:31:03

标签: oracle plsql

这是oracle函数之一。有一个名为c_adv_course_credit的游标,它接收2个参数。这两个参数使用where语句:

WHERE
    -- year
    cc.year = p_year AND
    -- rela_pk
    cc.sequence_number = p_sequence_number AND
    cc.closed_ind = 'N';

当我在oracle sql developer中运行它时:

SET SERVEROUTPUT ON
variable res varchar2(200);
EXECUTE :res := advp_test_cursor(2018, 92919);
select :res from dual;

结果文字始终为"not working"

这是完整的功能(不工作):

CREATE OR REPLACE Function SISD_OWNER.advp_test_cursor (
        p_sequence_number IN NUMBER, -- rela_pk
  p_year IN NUMBER  -- year
)
RETURN VARCHAR2     
IS
v_return_var VARCHAR2(300) := 'not working';

CURSOR c_adv_course_credit (
  p_sequence_number IN NUMBER,
  p_year IN NUMBER
)
IS
  SELECT 
    cc.EXTERNAL_COURSE_CD
  FROM
    adv_course_credit cc
  WHERE
    cc.year = p_year AND
    -- rela_pk
    cc.sequence_number = p_sequence_number AND
    cc.closed_ind = 'N';
BEGIN
  FOR v_at_rec IN c_adv_course_credit(p_sequence_number, p_year) LOOP
    v_return_var := v_at_rec.EXTERNAL_COURSE_CD;
    DBMS_OUTPUT.PUT_LINE('?output = ' || v_return_var);
    EXIT;
  END LOOP;    
  RETURN v_return_var;
END;

如果我将光标更改为使用硬编码数字,则该功能可以正常工作并返回实际结果。

WHERE
        -- year
        cc.year = 2018 AND
        -- rela_pk
        cc.sequence_number = 92919 AND
        cc.closed_ind = 'N';

2 个答案:

答案 0 :(得分:4)

您的功能定义为(忽略数据类型):

advp_test_cursor(p_sequence_number, p_year)

但你称之为

advp_test_cursor(2018, 92919);

其参数的方向错误。您需要翻转它们:

advp_test_cursor(92919, 2018);

或使用named parameter notation

advp_test_cursor(p_year=>2018, p_sequence_number=>92919)

或确实将两者结合起来:

advp_test_cursor(p_sequence_number=>92919, p_year=>2018)

答案 1 :(得分:0)

您不需要使用游标:

CREATE OR REPLACE Function SISD_OWNER.advp_test_cursor (
  p_sequence_number IN adv_course_credit.sequence_number%TYPE,
  p_year            IN adv_course_credit.year%TYPE
) RETURN adv_course_credit.EXTERNAL_COURSE_CD%TYPE
IS
  v_return_var adv_course_credit.EXTERNAL_COURSE_CD%TYPE;
BEGIN
  SELECT EXTERNAL_COURSE_CD
  INTO   v_return_var
  FROM   adv_course_credit
  WHERE  year            = p_year
  AND    sequence_number = p_sequence_number
  AND    closed_ind      = 'N';

  DBMS_OUTPUT.PUT_LINE('?output = ' || v_return_var);

  RETURN v_return_var;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    RETURN 'Not working';
END;