且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

选择一个列值并将其存储在变量oracle sql中

更新时间:2023-01-30 22:00:56

如果要使用rownumorder by,则必须在子查询中下达订单.没有其他方法可以保证您获得正确的值.

If you want to use rownum and order by you have to put the order by in a sub-query. There is no other way to guarantee that you get the correct value.

处理可能没有与您的查询匹配的id的可能性也是一种很好的做法.我添加了一个额外的begin... end;块来解决这个问题.

It's also good practice to deal with the possibility that there may not be an id that matches your query. I've added an additional begin... end; block to deal with this.

declare
   v_id a.id%type;
begin

   begin
      select id into v_id 
        from ( select id
                 from a 
                 where name = 'test' 
                 order by id desc )
       where rownum < 2 
             ;
    exception when no_data_found then
      v_id := null;
    end;

   dbms_output.put_line(v_id);
   doSomething(v_id);

end;
/

正如@raukh所指出的(虽然我正在写这篇文章!)问题是print,应该是dbms_output.put_line()

As @raukh noted (whilst I was writing this!) the problem is print, which should be dbms_output.put_line()