2014-09-01 31 views
1

我使用的是Oracle 11,該代碼似乎並不工作:PL/SQL「選擇..其中..在」使用本地表集合

procedure test() 
as 
    type StrTable is table of number; 

    --local variable 
    testTable StrTable; 

begin 
    testTable := StrTable(); 

    --add values 
    testTable.extend(3); 
    testTable(1) := 111; 
    testTable(2) := 222; 
    testTable(3) := 333; 

    --query 
    select * 
    from users 
    where id in testTable; <---------------- ERROR! 
end; 

顯示錯誤爲:

錯誤(427,31):PLS-00642:本地集合類型不能在SQL語句

允許如何解決這一問題?

+2

不,那是一個PL/SQL塊內聲明的嵌套表不能在查詢中使用。爲了能夠引用PL/SQL塊中的嵌套表,需要在模式級別聲明它。而且,PL/SQL塊內的'select'語句必須有'into'子句(它需要在某處存儲返回的值)。 – 2014-09-01 06:20:23

+0

tks關於'模式級別'的說明。關於「進入」條款,我知道它:),上面只是測試代碼 – jondinham 2014-09-01 06:23:00

回答

4

最簡單的選擇是在SQL中而不是在PL/SQL中定義集合。你的程序正在執行一個SELECT,它不會將數據返回到本地變量中,並且不會用於打開遊標 - 無論您是否使用集合,這都是不允許的。在我的例子中,我會做一個COUNT(*)到一個局部變量 - 你可能想要做其他事情。

-- Calling it StrTable when it's a table of numbers seems odd 
CREATE TYPE StrTable 
    IS TABLE OF NUMBER; 

CREATE PROCEDURE test 
AS 
    testTable StrTable; 

    l_cnt  pls_integer; 
BEGIN 
    testTable := StrTable(); 

    --add values 
    testTable.extend(3); 
    testTable(1) := 111; 
    testTable(2) := 222; 
    testTable(3) := 333; 

    -- query 
    SELECT COUNT(*) 
    INTO l_cnt 
    FROM users 
    WHERE id IN (SELECT column_value 
        FROM TABLE(testTable)); 

    dbms_output.put_line(l_cnt); 
END; 

而只是爲了顯示它的工作原理

SQL> exec test; 
3 

PL/SQL procedure successfully completed. 
+0

我實際上想要一個'where .. in testTable',而不是'從表(testTable)' – jondinham 2014-09-01 06:33:29

+0

@JonDinham - 這只是'WHERE some_value IN(SELECT column_value FROM TABLE(testTable))'。如果你想編輯你的問題來包含一個物理表格和你想要完成的更具體的解釋,我很樂意編輯我的答案。 – 2014-09-01 06:35:58

+0

我現在可以做到了,我使用「where id in(select * from table(testTable))」。賈斯汀 – jondinham 2014-09-01 06:40:32