22

我有一个函数会返回一条 type 的记录my_table%ROWTYPE,在调用者中,我可以检查返回的记录是否为空,但是 PL/SQL 抱怨 if 语句

PLS-00306:调用“IS NOT NULL”时参数的数量或类型错误

这是我的代码:

v_record my_table%ROWTYPE;
v_row_id my_table.row_id%TYPE := 123456;
begin
    v_record := myfunction(v_row_id)
    if (v_record is not null) then
        -- do something
    end if;
end;

function myfunction(p_row_id in my_table.row_id%TYPE) return my_table%ROWTYPE is
    v_record_out my_table%ROWTYPE := null;
begin
    select * into v_record_out from my_table
    where row_id = p_row_id;
    return v_record_out;
end myfunction;

谢谢。

4

2 回答 2

33

据我所知,这是不可能的。不过,检查PRIMARY KEYorNOT NULL列就足够了。


你可以检查一下v_record.row_id IS NULL

NO_DATA_FOUND但是,当找不到记录时,您的函数会抛出异常。

于 2011-08-26T16:42:11.237 回答
3

您无法测试此变量是否不存在,因此有两种方法可以解决。检查是否存在单个元素。我不喜欢这样,因为这意味着如果有任何更改您的代码将不再有效。相反,为什么不在那里没有数据时引发异常:

我意识到others异常中的异常非常顽皮,但它只会在我不应该消失的时候真正抓住我的桌子消失,而没有别的。

v_record my_table%ROWTYPE;
v_row_id my_table.row_id%TYPE := 123456;

begin
    v_record := myfunction(v_row_id)
exception when others then
        -- do something
end;

function myfunction(p_row_id in my_table.row_id%TYPE) return my_table%ROWTYPE is
    v_record_out my_table%ROWTYPE := null;

cursor c_record_out(c_row_id char) is
 select * 
   from my_table
  where row_id = p_row_id;

begin
   open c_record_out(p_row_id);
   fetch c_record_out into v_record_out;

   if c_record_out%NOTFOUND then
      raise_application_error(-20001,'no data);
   end if;
   close c_record_out;
return v_record_out;
end myfunction;
于 2011-08-27T08:06:47.753 回答