Split the String in SQL 400
Reference : SYSTOOLS/SPLIT
Parameters:
SPLIT table function accepts three parameters.
- INPUT_LIST (Input List) - String(s) that needs to be split.
- DELIMITER (Delimiter) - String or character that needs to be considered as separator. Both Input List and Delimiter are mandatory parameters.
- ESCAPE (Escape) - A character string of length '1' that is to be used as escape character. Delimiter followed by escape character would not be considered as separator. This is an optional parameter.
E.g.:
Split the string into words (consider blank space as delimiter).
In the above query, we are only passing the two mandatory parameters Input list and Delimiter.
This table function returns the below two columns.
- ORDINAL_POSITION (Ordinal Position) - Position of the substring in the result. Starts from 1.
- ELEMENT (Element) - Substring that is split.
Result of the above query would be as below.
In case if we need some of the delimiters to be skipped followed by a specific (escape) character, we can pass the optional parameter ESCAPE with the corresponding character.
- We are passing back slash (\) as escape character.
- Table function would ignore the delimiter followed by the escape character and would not split the the string.
- Escape character wouldn't present in the substring split.
In both these examples, we are passing the string exclusively which may not always be the case if we need to use this function in the procedures or programs.
We can use pass the columns from the other tables in query and specify the delimiter.
Let's have a look at another simple example.
In the above query,
- Line - 1: TESTTABLE is a table with just one character column (CHARFIELD).
- Line - 2: Table function SPLIT from SYSTOOLS library.
- Line - 3: First parameter INPUT_LIST for SPLIT table function. We are passing one column CHARFIELD from the table TESTTABLE. We are using TRIM so any leading or trailing blanks wouldn't be considered.
- Line - 4: Second parameter DELIMITER for SPLIT table function. We are passing blanks, so string would be split into words like in previous example.
- We aren't passing the third and optional parameter ESCAPE. This can be passed if required.
Let's have a look at the result.
In the result,
- First column CHARFIELD is from the table TESTTABLE, original data in the table before it is split.
- Second column ORDINAL_POSITION returns the position of the substring.
- Third Column ELEMENT returns the substring.
There would be multiple rows of substrings for each row in the original table.
*This function is only available since IBM i 7.3 TR6 and higher.
No comments:
Post a Comment