将整个列存储在存储过程内的变量中

时间:2015-07-03 14:30:16

标签: oracle stored-procedures plsql

我在包中有一个复杂的存储过程。在这个SP中,我需要查询一个表来获取有关一列的所有数据,然后使用它来检查" IF"中的一些其他条件。声明。 这就是我在做的事情:

--declare a variable to store the holidays
l_holidays MySchema. HolidayTable.DateColumn%TYPE

-- populate this variable 
Select a.DateColumn into l_holidays
from MySchema. HolidayTable a;

-- using this variable inside an "IF" statement
IF (current_Date IN l_holidays)
THEN
    -- do something
ELSE
     -- do something
END IF;

每次运行时,都会出现以下错误

ORA-01422: exact fetch returns more than requested number of rows

我知道这是因为我试图使用" INTO"填充整个列。条款。但我不知道其他任何方式。

2 个答案:

答案 0 :(得分:1)

创建collection并使用BULK COLLECT INTO

CREATE PROCEDURE my_proc (
  current_date  IN MySchema.HolidayTable.DateColumn%TYPE
)
AS
  TYPE date_tab IS TABLE OF MySchema.HolidayTable.DateColumn%TYPE;
  l_holidays date_tab;
BEGIN
  SELECT DateColumn
  BULK COLLECT INTO l_holidays
  FROM   MySchema.HolidayTable;

  IF (current_Date MEMBER OF l_holidays)
  THEN
    NULL; -- do something
  ELSE
    NULL; -- do something
  END IF;
END;

否则你只能在选择中进行测试:

CREATE PROCEDURE my_proc (
  current_date  IN MySchema.HolidayTable.DateColumn%TYPE
)
AS
  has_date NUMBER(1,0);
BEGIN
  SELECT CASE WHEN EXISTS ( SELECT 'X'
                            FROM   MySchema.HolidayTable
                            WHERE  DateColumn = Current_Date )
         THEN 1
         ELSE 0
         END
  INTO   has_date
  FROM   DUAL;

  IF has_date = 1
  THEN
    NULL; -- do something
  ELSE
    NULL; -- do something
  END IF;
END;

答案 1 :(得分:0)

Hello similarly you can use this query to fulfill your requirements

SET serveroutput ON;
SET sqlbl ON;
DECLARE
type l_holiday
IS
  TABLE OF DATE;
  tab_holiday l_holiday;
BEGIN
  SELECT a.dt BULK COLLECT
  INTO tab_holiday
  FROM
    (SELECT SYSDATE dt FROM DUAL
    UNION
    SELECT SYSDATE+1 dt FROM DUAL
    UNION
    SELECT SYSDATE+2 dt FROM DUAL
    UNION
    SELECT SYSDATE+3 FROM DUAL
    )a;
  IF tab_holiday.COUNT > 0 THEN
    IF SYSDATE MEMBER OF tab_holiday THEN
      dbms_output.put_line('yes working');
    ELSE
      dbms_output.put_line('awsme working');
    END IF;
  END IF;
END;