Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

plsql - PL/SQL - comma separated list within IN CLAUSE

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...