Connect with Db2, Informix, Netezza, open source, and other data experts to gain value from your data, share insights, and solve problems.
Posted by: Serge RielauHaving demonstrated how to aggregate strings using XML in an earlier post I have been asked about how to do the inverse.Giving a a string and a defined separator, produce a table with one row per substring. So here is what I came up with:
CREATE OR REPLACE FUNCTION PK_BASE.SPLIT(text VARCHAR(32000), split VARCHAR(10))RETURNS TABLE(column_values VARCHAR(60))RETURN WITH rec(rn, column_value, pos) AS (VALUES (1, VARCHAR(SUBSTR(text, 1, DECODE(INSTR(text, split, 1), 0, LENGTH(text), INSTR(text, split, 1) - 1)), 255), INSTR(text, split, 1) + LENGTH(split)) UNION ALL SELECT rn + 1, VARCHAR(SUBSTR(text, pos, DECODE(INSTR(text, split, pos), 0, LENGTH(text) - pos + 1, INSTR(text, split, pos) - pos)), 255), INSTR(text, split, pos) + LENGTH(split) FROM rec WHERE rn < 30000 AND pos > LENGTH(split)) SELECT column_value FROM rec;
SELECT * FROM TABLE(PK_BASE.SPLIT('123/45/6/789/abc/def/ghi', '/')); COLUMN_VALUES-------------------------123456789abcdefghi 10 record(s) selected.