PL/SQL - comma separated list within IN CLAUSE

冷暖自知 提交于 2019-11-29 05:19:24

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

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

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

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'));

You can use XMLTABLE as follows

SELECT * FROM users 
WHERE user_id IN (SELECT to_number(column_value) FROM XMLTABLE(v_list));

I have tried to find a solution for that too but never succeeded. You can build the query as a string and then run EXECUTE IMMEDIATE, see http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/dynamic.htm#i14500.

That said, it just occurred to me that the argument of an IN clause can be a sub-select:

SELECT * FROM users 
WHERE user_id IN (SELECT something FROM somewhere)

so, is it possible to expose the checkbox values as a stored function? Then you might be able to do something like

SELECT * FROM users
WHERE user_id IN (SELECT my_package.checkbox_func FROM dual)

Personally, i like this approach:

with t as (select 'a,b,c,d,e' str from dual)
--
select val
from t, xmltable('/root/e/text()'
                 passing xmltype('<root><e>' || replace(t.str,',','</e><e>')|| '</e></root>')
                 columns val varchar2(10) path '/'
                )

Which can be found among other examples in Thread: Split Comma Delimited String Oracle

If you feel like swamping in even more options, visit the OTN plsql forums.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!