Oracle gem of the day: split in PL/SQL

jdavidb on 2006-07-21T13:01:59

This is actually prettier and more elegant than I usually get for PL/SQL. :) The routine relies on a function

betwnstr
, which you may find in Feuerstein and Pribyl's Oracle PL/SQL Programming from O'Reilly, 3rd edition, page 216, or implement yourself. Incidentally, one bug I had along the way was using SUBSTR here without thinking about what I really wanted to do.

Generalizing to take any arbitrary character to split on as a parameter is left as an exercise to the reader. As is generalizing to take any arbitrary string, followed by generalizing to take any arbitrary regular expression.

FUNCTION comma_split(p_text VARCHAR2)
RETURN OWA_TEXT.VC_ARR
IS
  v_array OWA_TEXT.VC_ARR;
  v_lastpos INTEGER := 0;
  v_pos INTEGER;
  v_count INTEGER := 0;
BEGIN
  WHILE v_lastpos <= LENGTH(p_text)
  LOOP
    v_count := v_count + 1;
    v_pos := INSTR(p_text, ',', 1, v_count);
    IF v_pos = 0
    THEN
      v_pos := LENGTH(p_text) + 1;
    END IF;
    v_array(v_count) := betwnstr(p_text, v_lastpos + 1, v_pos - 1);
    v_lastpos := v_pos;
  END LOOP;
  RETURN v_array;
END comma_split;