如何根据 Oracle 中的动态列表检查 IN 条件?
编辑:更改标题以适合下面的代码。
我试图从 Oracle 表中检索可接受值的列表,然后对另一个表执行 SELECT,同时将某些字段与所述列表进行比较。
我试图用光标来做到这一点(如下所示),但是失败了。
DECLARE
TYPE gcur IS REF CURSOR;
TYPE list_record IS TABLE OF my_table.my_field%TYPE;
c_GENERIC gcur;
c_LIST list_record;
BEGIN
OPEN c_GENERIC FOR
SELECT my_field FROM my_table
WHERE some_field = some_value;
FETCH c_GENERIC BULK COLLECT INTO c_LIST;
-- try to check against list
SELECT * FROM some_other_table
WHERE some_critical_field IN c_LIST;
END
基本上,我想做的是将可接受的值列表缓存到变量中,因为稍后我将反复检查它。
在 Oracle 中如何执行此操作?
EDIT: changed the title to fit the code below.
I'm trying to retrieve a list of acceptable values from an Oracle table, then performing a SELECT against another while comparing some fields against said list.
I was trying to do this with cursors (like below), but this fails.
DECLARE
TYPE gcur IS REF CURSOR;
TYPE list_record IS TABLE OF my_table.my_field%TYPE;
c_GENERIC gcur;
c_LIST list_record;
BEGIN
OPEN c_GENERIC FOR
SELECT my_field FROM my_table
WHERE some_field = some_value;
FETCH c_GENERIC BULK COLLECT INTO c_LIST;
-- try to check against list
SELECT * FROM some_other_table
WHERE some_critical_field IN c_LIST;
END
Basically, what I'm trying to do is to cache the acceptable values list into a variable, because I will be checking against it repeatedly later.
How do you perform this in Oracle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们可以使用集合来存储值来满足您的目的,但它们需要声明为 SQL 类型:
这是因为我们不能在 SQL 语句中使用 PL/SQL 类型。唉,这意味着我们不能使用
%TYPE
或%ROWTYPE
,因为它们是 PL/SQL 关键字。您的程序将如下所示:
如果值在表中,则没有其他方法可以将它们放入变量中:)
不一定。如果您只使用这些值一次,那么子查询肯定是更好的方法。但是当您想在多个离散查询中使用相同的值时,然后填充一个集合是更有效的方法,
在 11g 企业版中,我们可以选择使用结果集缓存。 这是一种更好的解决方案,但并不适合所有表。
We can use collections to store values to suit your purposes, but they need to be declared as SQL types:
This is because we cannot use PL/SQL types in SQL statements. Alas this means we cannot use
%TYPE
or%ROWTYPE
, because they are PL/SQL keywords.Your procedure would then look like this:
If the values are in a table there is no other way to get them into a variable :)
Not necessarily. If you're only using the values once then the sub-query is certainly the better approach. But as you want to use the same values in a number of discrete queries then populating a collection is the more efficient approach.
In 11g Enterprise Edition we have the option to use result set caching. This is a much better solution, but one which is not suited for all tables.
为什么拉列表而不是使用半连接?
Why pull the list instead of using a semi-join?