将单个列提取到数组中

时间:2011-12-19 21:03:29

标签: oracle plsql oracle10g

我有一个包含varchar2类型的column_id的表。该表可能包含1,0行或多行。我的业务逻辑取决于每种情况。

我正在尝试将列提取到一个数组中但我得到了奇怪的错误(鉴于我对pl / sql的了解有限)

  TYPE t_col_id IS TABLE OF TEST_TABLE.COLUMN_ID%TYPE INDEX BY BINARY_INTEGER;
  AR_COL_ID T_COL_ID;

然后我试图将数据提取到此数组

SELECT COLUMN_ID INTO AR_SIM_ID FROM TEST_TABLE WHERE COLUMN_ID = 1;

我收到此错误

Error(7,3): PL/SQL: SQL Statement ignored
Error(7,25): PLS-00597: expression 'AR_SIM_ID' in the INTO list is of wrong type
Error(7,35): PL/SQL: ORA-00904: : invalid identifier

我有什么遗失的东西吗?我的原始代码将此数组用作

BEGIN
   -- FETCH ARRAY QUERY
   IF (AR_SIM_ID.LENGTH = 0) THEN 
      -- BUSINESS LOGIC 1
   ELSE
      -- BUSINESS LOGIC 2
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         -- BUSINESS LOGIC 3
END;

2 个答案:

答案 0 :(得分:4)

您必须使用INTO

,而不是使用BULK COLLECT INTO
DECLARE
   TYPE t_col_id IS TABLE OF TEST_TABLE.COLUMN_ID%TYPE INDEX BY BINARY_INTEGER;
   AR_COL_ID T_COL_ID;
BEGIN
   SELECT COLUMN_ID 
     BULK COLLECT INTO AR_SIM_ID 
     FROM TEST_TABLE
    WHERE COLUMN_ID = 1;

   IF AR_SIM_ID.LENGTH = 0 THEN 
      -- BUSINESS LOGIC 1
   ELSE
      -- BUSINESS LOGIC 2
   END IF;

EXCEPTION
   WHEN NO_DATA_FOUND THEN
      -- BUSINESS LOGIC 3
END;

但是你不能在这种情况下使用COUNT吗?

DECLARE
   numRows   NUMBER;
BEGIN
   SELECT COUNT(COLUMN_ID)
     INTO numRows
     FROM TEST_TABLE 
    WHERE COLUMN_ID = 1;

   IF numRows = 0 THEN 
      -- BUSINESS LOGIC 1
   ELSE
      -- BUSINESS LOGIC 2, 3, etc...
   END IF;
END;

答案 1 :(得分:0)

一个。如果要将所有行都放到plsq表中 - 您需要批量收集 湾如果您只想知道表格中有多少行,您应该这样做:

 SELECT count(*) INTO v_count from TEST_TABLE where COLUMN_ID = 1;

℃。我不喜欢将EXCEPTION范围用作程序工作流程的一部分 - 我会这样做:

IF v_count = 0 THEN  
-- BUSINESS LOGIC 1  
ELSIF v_count = 1 THEN  
-- BUSINESS LOGIC 2  
ELSE  
-- BUSINESS LOGIC 3  
END IF;