gpt4 book ai didi

oracle - 在 'IN' 子句中使用绑定(bind)变量

转载 作者:行者123 更新时间:2023-12-02 08:06:18 25 4
gpt4 key购买 nike

我想将数字列表查询到 plsql 变量中,并在另一个 SQL 查询的 in 子句中使用它。我在下面创建了一个我想要做的测试用例。

我在谷歌上搜索了解决方案,我认为它一定有可能,但我就是无法运行它。请帮我解决编译问题。

CREATE OR REPLACE PROCEDURE PROCEDURE1 
as
type t_id is table of number;
v_ids t_id;
v_user_ids number;
BEGIN

-- fill variable v_id with id's, user_id is of type number
select user_id
bulk collect into v_ids
from user_users;

-- then at a later stage ... issue a query using v_id in the in clause
select user_id into v_user_ids from user_users
-- this line does not compile ( local collection type not allowed in SQL statements)
where user_id in ( v_ids );

END PROCEDURE1;

最佳答案

使用 SQL 类型:

SQL> create type t_id is table of number;
2 /

Type created.

SQL> CREATE OR REPLACE PROCEDURE PROCEDURE1
2 as
3 v_ids t_id;
4 v_user_ids number;
5 BEGIN
6
7 -- fill variable v_id with id's, user_id is of type number
8 select user_id
9 bulk collect into v_ids
10 from user_users
11 where user_id between 100 and 120;
12
13 select user_id into v_user_ids
14 from user_users
15 where user_id in (select /*+ cardinality(t, 10) */ t.column_value from table(v_ids) t)
16 and rownum = 1;
17
18 dbms_output.put_line(v_user_ids);
19
20 END PROCEDURE1;
21 /

Procedure created.

SQL> exec procedure1
100

其中 cardinality(t, 10) 应该是对数组中有多少元素的合理猜测。

注意:像您一样使用无限制的批量收集:

  8    select user_id
9 bulk collect into v_ids
10 from user_users;
如果您的数组最终可能有数千行或更多行,那么通常情况不太好,因为您对内存施加了太大的压力,最终会使代码崩溃。您最好使用显式游标 open x for .. 和带有 limit 子句的循环中的批量获取,即 fetch xbulkcollect into v_ids limit 100 和批量处理,例如 100-1000 个。

关于oracle - 在 'IN' 子句中使用绑定(bind)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13627493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com