将列的前两个值提取到存储过程中的两个不同变量中

时间:2018-01-24 05:31:13

标签: oracle stored-procedures

假设table_1由一列(table_no)组成,select * from table_1为你提供了5个table_no值。现在我想将table_no的前两个值存储到两个不同的变量中。我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果只需要2个值,请尝试使用MIN和MAX函数。像这样:

DECLARE
  var1 NUMBER;
  var2 NUMBER;
BEGIN
   SELECT MIN(table_no), MAX(table_no) INTO var1, var2 FROM
     (SELECT table_no FROM (SELECT table_no FROM table_1 ORDER BY table_no ) 
      WHERE rownum <= 2);
END;

答案 1 :(得分:0)

SQL> create table t as select trunc(dbms_random.value(1,20)) x from dual connect by level <= 5;

Table created.

SQL> select * from t;

         X
----------
        10
        13
         8
        10
        16

SQL> select
  2    max(decode(rn,1,x)),
  3    max(decode(rn,2,x))
  4  from
  5   ( select row_number() over ( order by x ) rn, x from t ) ;

MAX(DECODE(RN,1,X)) MAX(DECODE(RN,2,X))
------------------- -------------------
                  8                  10