Oracle:函数只返回null

时间:2013-05-13 12:45:45

标签: sql oracle function plsql

以下函数应返回与会议表中存储的特定会议相关的信息:

CREATE TABLE  "MEETING" 
   (    "MEETING_ID" NUMBER(10,0) NOT NULL ENABLE, 
    "TIME" TIMESTAMP (4) NOT NULL ENABLE, 
    "LOCATION" VARCHAR2(40), 
    "MAP_HREF" VARCHAR2(140), 
    "FK_INTEREST_ID" CHAR(4) NOT NULL ENABLE, 
    "ADDITIONAL_INFO" CLOB, 
    "PASSED" NUMBER(1,0), 
    "TITLE" VARCHAR2(20), 
     CONSTRAINT "MEETING_PK" PRIMARY KEY ("MEETING_ID") ENABLE
   ) ;

代码编译得很好,并且运行良好。

但是,如果会议存在,则仅返回null。如果会议不存在,则例外会正确打印“未知任命”。

CREATE OR REPLACE FUNCTION GetMeeting
                    (meetingnumber MEETING.MEETING_ID%TYPE)
RETURN VARCHAR
IS
    CURSOR current_meeting(meetingnumber MEETING.MEETING_ID%TYPE)
    IS
        SELECT TITLE
        FROM MEETING
        WHERE MEETING_ID = meetingnumber;

    r_meeting current_meeting%ROWTYPE;
BEGIN
    OPEN current_meeting(meetingnumber);

    FETCH current_meeting INTO r_meeting;

    IF current_meeting%NOTFOUND THEN
        r_meeting.TITLE := 'UNKNOWN APPOINTMENT';
    END IF;

    CLOSE current_meeting;

    RETURN r_meeting.TITLE;
END;


SELECT GetMeeting (27) appointment
FROM MEETING;

4 个答案:

答案 0 :(得分:2)

似乎这是使用游标的练习?它比它需要的复杂得多。尝试类似(未经测试的):

create or replace function get_meeting(i_meetingnumber MEETING.MEETING_ID%TYPE)
RETURN VARCHAR2
IS
  l_title MEETING.TITLE%TYPE;
BEGIN

  select title
  into l_title
  FROM MEETING
  WHERE MEETING_ID = i_meetingnumber;

  return l_title;
EXCEPTION
  when no_data_found then
    return 'UNKNOWN APPOINTMENT';
  when others then raise;
END;

将这个小逻辑放在函数中也没有必要,我只需根据需要选择它(通过更大的SQL的连接或单独的更大的pl / sql过程)

另外,我注意到你的原始函数返回VARCHAR,其中title是VARCHAR2。如果转换是由Oracle隐式完成的,那么也不确定,但值得一提的是。

答案 1 :(得分:1)

SELECT NVL(TITLE, 'UNKNOWN APPOINTMENT') FROM MEETING WHERE MEETING_ID = meetingnumber;

更干净。

答案 2 :(得分:0)

检查以下声明:

IF r_meeting%NOTFOUND THEN
        r_meeting.TITLE := 'UNKNOWN APPOINTMENT';
        END IF;

        CLOSE current_meeting;

        RETURN r_meeting.TITLE;
    END;

答案 3 :(得分:0)

PL / SQL函数运行正常。它返回所需的结果,但您的选择返回尽可能多的数据集,如MEETING中所示。您应该从双重选择。