简体   繁体   中英

PL-SQL stored procedure split string

What I would like to do is this:

In java I have an array like ['AB','BC','CD','DE'] which I want to concat to something like "AB,BC,CD,DE" and send it to the procedure as an argument.

In the procedure, my idea is, I would like to do something like

v_passedArgs --(AB,BC,CD,DE)

SELECT * FROM SOME_TABLE WHERE SOME_COL IN (v_passedArgs.split(','))

Is it possible to do something like that or maybe you have another idea? Thank you

You can create a split function in the database and use it for splitting a string in SQL which has delimiters(',' in your example)

Is there a function to split a string in PL/SQL?

Refer the above link to create a split function and use it in your select statement

You have to create your own function.

You can work with an Oracle PL/SQL collection ; here is a piece of code to return such a collection, from an input string list ( p_list ) with a given separator ( p_sep ):

CREATE OR REPLACE TYPE t_my_list AS TABLE OF VARCHAR2(100);
CREATE OR REPLACE
FUNCTION cto_table(p_sep in Varchar2, p_list IN VARCHAR2)
  RETURN t_my_list
AS
  l_string VARCHAR2(32767) := p_list || p_sep;
  l_sep_index PLS_INTEGER;
  l_index PLS_INTEGER := 1;
  l_tab t_my_list     := t_my_list();
BEGIN
  LOOP
    l_sep_index := INSTR(l_string, p_sep, l_index);
    EXIT
  WHEN l_sep_index = 0;
    l_tab.EXTEND;
    l_tab(l_tab.COUNT) := TRIM(SUBSTR(l_string,l_index,l_sep_index - l_index));
    l_index            := l_sep_index + 1;
  END LOOP;
  RETURN l_tab;
END cto_table;
/

Then how to use it with the TABLE keyword in your SELECT - the TABLE keyword converts the collection into a object usable inside Oracle SQL queries:

SELECT * FROM SOME_TABLE WHERE SOME_COL IN (
      select * from TABLE(cto_table(',', v_passedArgs))
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM