gpt4 book ai didi

sql - 如何在使用变量的动态查询中指定 IN 子句?

转载 作者:行者123 更新时间:2023-12-01 00:58:16 24 4
gpt4 key购买 nike

在 PL/SQL 中,您可以使用连接指定 IN 运算符的值:

v_sql := 'select field1
from table1
where field2 in (' || v_list || ')';

是否可以使用变量做同样的事情?
v_sql := 'select field1
from table1
where field2 in (:v_list)';

如果是这样,怎么做?

编辑:引用 Marcin 的回答,我如何从结果表中进行选择?
declare

cursor c_get_csv_as_tables is
select in_list(food_list) food_list
from emp_food
where emp_type = 'PERM';

cursor c_get_food_list (v_food_table varchar2Table)is
select *
from v_food_table;

begin
for i in c_get_csv_as_tables loop
for j in c_get_food_list(i.food_list) loop
dbms_output.put_line(j.element);
end loop;
end loop;
end;

我收到以下错误:
ORA-06550: line 10, column 6:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 9, column 1:
PL/SQL: SQL Statement ignored
ORA-06550: line 15, column 34:
PLS-00364: loop index variable 'J' use is invalid
ORA-06550: line 15, column 13:
PL/SQL: Statement ignored

最佳答案

就像在@Sathya 链接中一样,您可以绑定(bind)可变数组(我以@Codo 为例):

CREATE OR REPLACE TYPE str_tab_type IS VARRAY(10) OF VARCHAR2(200);
/
DECLARE
l_str_tab str_tab_type;
l_count NUMBER;
v_sql varchar2(3000);
BEGIN
l_str_tab := str_tab_type();
l_str_tab.extend(2);
l_str_tab(1) := 'TABLE';
l_str_tab(2) := 'INDEX';

v_sql := 'SELECT COUNT(*) FROM all_objects WHERE object_type IN (SELECT COLUMN_VALUE FROM TABLE(:v_list))';

execute immediate v_sql into l_count using l_str_tab;

dbms_output.put_line(l_count);
END;
/

更新:第一个命令可以替换为:
CREATE OR REPLACE TYPE str_tab_type IS TABLE OF VARCHAR2(200);
/

然后调用:
l_str_tab.extend(1);

每当你添加一个值

关于sql - 如何在使用变量的动态查询中指定 IN 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967652/

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