问题
I have a table TableA with a tilde operated column ColumnA
TableA
**ColumnA**
123~abc~def~~~~~ghi~j~k~lmn~op~~~
231~a~dfg~wer~~~~~~~hijkl~~~
As we can see in the above two rows, it is '~' separated. I basically want to separate the values into individual columns. There are 15 '~' operators.
My output table should be something like
Col1 Col2 Col3 Col4 . . .. . . .. .. .. .. .
123 abc def . .. . .. .. ... .. . . .
I have a query in DB2 which will do this but it requires 15 subqueries to achieve this task as there are 15 '~' operators. Given below:
SELECT substr(ColumnA, 1, LOCATE('~', ColumnA)-1) AS Col1,
substr(ColumnA, charindex('~', ColumnA)+1, LEN(ColumnA)) AS Other
FROM TableA
I am separating Col1 only by the above query. If I wish to separate 15 columns, I will have to subquery this 15 times.
Is there a better way to do this?
Thank you
回答1:
Someone was kind enough to write this split function for DB2
http://www.mcpressonline.com/sql/techtip-create-an-sql-function-to-split-a-delimited-list.html
CREATE FUNCTION QGPL.SPLIT (
@Data VARCHAR(32000),
@Delimiter VARCHAR(5))
RETURNS TABLE (
ID INT,
VALUE VARCHAR(256))
LANGUAGE SQL
DISALLOW PARALLEL
DETERMINISTIC
NOT FENCED
RETURN
WITH CTE_Items (ID,StartString,StopString) AS
(
SELECT
1 AS ID
,1 AS StartString
,LOCATE(@Delimiter, @Data) AS StopString
FROM SYSIBM.SYSDUMMY1
WHERE LENGTH(@Delimiter)>0
AND LENGTH(@Data)>0
UNION ALL
SELECT
ID + 1
,StopString + LENGTH(@Delimiter)
,LOCATE(@Delimiter, @Data, StopString + LENGTH(@Delimiter))
FROM
CTE_Items
WHERE
StopString > 0
)
SELECT ID, SUBSTRING(@Data,StartString,
CASE WHEN StopString=0
THEN LENGTH(@Data)
ELSE StopString-StartString END)
FROM CTE_Items;
来源:https://stackoverflow.com/questions/25188979/how-can-we-parse-a-tilde-delimited-column-in-sql-to-create-several-columns