如何在 Oracle SQL 语句中使用集合
我想编写一个 Oracle 函数,它通过多个步骤将一些数据收集到一个集合变量中,并在 SELECT 查询中使用该集合数据,就像这个非常简化的示例一样:
CREATE OR REPLACE FUNCTION TESTFUNC01 RETURN VARCHAR2 AS
-- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER"
MyList INT_LIST := INT_LIST();
MyName VARCHAR2(512);
BEGIN
MyList.Extend(3);
MyList(0) := 1;
MyList(1) := 2;
MyList(2) := 3;
SELECT Name INTO MyName
FROM Item WHERE ItemId NOT IN MyList;
RETURN MyName;
END TESTFUNC01;
不幸的是,“NOT IN MyList”部分不是有效的 SQL。有办法实现这一点吗?
I want to write an Oracle function that collects some data in multiple steps into a collection variable and use that collection data within a SELECT query like in this very simplified example:
CREATE OR REPLACE FUNCTION TESTFUNC01 RETURN VARCHAR2 AS
-- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER"
MyList INT_LIST := INT_LIST();
MyName VARCHAR2(512);
BEGIN
MyList.Extend(3);
MyList(0) := 1;
MyList(1) := 2;
MyList(2) := 3;
SELECT Name INTO MyName
FROM Item WHERE ItemId NOT IN MyList;
RETURN MyName;
END TESTFUNC01;
Unfortunately the part "NOT IN MyList" is no valid SQL. Is there a way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在寻找的是
table
函数:What you're looking for is the
table
function:如果您使用 Oracle 10,您可以使用集合扩展:
有关更多详细信息,请参阅这篇文章< /a>
If your using oracle 10 you could use the collections extensions:
for more details see this post
您可以这样做:
请注意,我还更改了列表索引。从 1(不是 0)开始。
You can do it like this:
Note that I've also changed the list indices. The start with 1 (not 0).
这看起来像一个 PL/SQL 声明。SELECT 语句使用 SQL 引擎。这意味着您需要在 SQL 中声明您的 TYPE。
然后您可以在 SELECT 语句中使用它:
当然,您需要确保您的查询仅返回一行,或者您的程序处理 TOO_MANY_ROWS 异常。
That looks like a PL/SQL declaration. SELECT statements use the SQL engine. This means you need to declare your TYPE in SQL.
Then you can use it in a SELECT statement:
Of course, you need to make sure that your query returns only one row, or that your program handles the TOO_MANY_ROWS exception.