Get a Substring between Specified Positions/Separators in DB2
【Question】
I have a number of strings like this:
aaa/bbb/ccc/ddd/eee
aaa/bbb/ccc
aaa/bbb/ccc/xxx/123
I am using DB2 where I need to find the position of the 1st slash and the 2nd slash and then get data between them, and then find the positoon of the 3rd slash and get data between it and the 2nd slash, etc.
【Answer】
Find positions of the slashes using DB2’s locate function and then get the substring with substr function. To get the substring between the 1st slash and the 2nd slash:
select substr(str,locate(‘/’,str)+1,locate(‘/’,str,locate(‘/’,str)+1-locate(‘/’,str))-1) from stb
In the above locate function the 3rd parameter gets the start position and the end position of a substring. A nested query is needed to find the position of the 2nd or nth slash. It’s hard to code all these locate query in one statement dynamically. It’s even harder to do it in the stored procedure.
SPL (Structured Process Language) offers related functions to handle it effortlessly. Here’s the SPL script:
A |
|
1 |
$select str from stb |
2 |
=A1.(str.array("/")(begin+1)) |
:begin is the specified start position. For example, get data between the 2nd slash and the 3rd slash when begin’s value is 2 and you will have the following result:
esProc provides JDBC interface to be easily integrated into another application. Refer to How to Call an SPL Script in Java to learn more.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL