PL/SQL - IN CLAUSE 中的逗号分隔列表 [英] PL/SQL - comma separated list within IN CLAUSE

查看:33
本文介绍了PL/SQL - IN CLAUSE 中的逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让 pl/sql 代码块工作.在我的程序的顶部,我从我的 oracle apex 应用程序中获取了一些关于选中哪些复选框的数据.因为包含复选框的报告是动态生成的,所以我必须遍历

I am having trouble getting a block of pl/sql code to work. In the top of my procedure I get some data from my oracle apex application on what checkboxes are checked. Because the report that contains the checkboxes is generated dynamically I have to loop through the

APEX_APPLICATION.G_F01 

列出并生成一个逗号分隔的字符串,如下所示

list and generate a comma separated string which looks like this

v_list VARCHAR2(255) := (1,3,5,9,10);

我想稍后查询该列表并将 v_list 放在 IN 子句上

I want to then query on that list later and place the v_list on an IN clause like so

SELECT * FROM users 
WHERE user_id IN (v_list);

这当然会引发错误.我的问题是我可以将 v_list 转换为什么,以便能够将它插入到 pl/sql 过程中查询的 IN 子句中?

This of course throws an error. My question is what can I convert the v_list to in order to be able to insert it into a IN clause in a query within a pl/sql procedure?

推荐答案

如果 users 很小并且 user_id 不包含逗号,您可以使用:

If users is small and user_id doesn't contain commas, you could use:

SELECT * FROM users WHERE ',' || v_list || ',' LIKE '%,'||user_id||',%'

这个查询并不是最优的,因为它不能使用 user_id 上的索引.

This query is not optimal though because it can't use indexes on user_id.

我建议您使用流水线函数,该函数返回您可以直接查询的 NUMBER 表.例如:

I advise you to use a pipelined function that returns a table of NUMBER that you can query directly. For example:

CREATE TYPE tab_number IS TABLE OF NUMBER;
/
CREATE OR REPLACE FUNCTION string_to_table_num(p VARCHAR2)
   RETURN tab_number
   PIPELINED IS
BEGIN
   FOR cc IN (SELECT rtrim(regexp_substr(str, '[^,]*,', 1, level), ',') res
                FROM (SELECT p || ',' str FROM dual)
              CONNECT BY level <= length(str) 
                                  - length(replace(str, ',', ''))) LOOP
      PIPE ROW(cc.res);
   END LOOP;
END;
/

然后您将能够构建查询,例如:

You would then be able to build queries such as:

SELECT * 
  FROM users 
 WHERE user_id IN (SELECT *
                     FROM TABLE(string_to_table_num('1,2,3,4,5'));

这篇关于PL/SQL - IN CLAUSE 中的逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆