How to split a string value based on a delimiter in DB2

后端 未结 10 1600
失恋的感觉
失恋的感觉 2020-11-27 08:09

How do you split a string value in DB2?

For example, given the value:

CHG-FFH.

I want to split on the dash (-), which would resul

10条回答
  •  有刺的猬
    2020-11-27 08:26

    This answer is not totally different, but it impements LOCATE_IN_STRING in a more flexible way which is useful, for example, if you have restrictions not to use functions.

    To get the nth string delimited by the character '-' as in your example:

    SUBSTR(THESTRING, LOCATE_IN_STRING(THESTRING, '-', 1,  n - 1) + 1, 
    LOCATE_IN_STRING(THESTRING||'-', '-', 1,  n) - LOCATE_IN_STRING(THESTRING, '-', 1,  n - 1) - 1) 
                            
    

    If you replace each occurrence of n by the column number you want, this construct will return the nth column's contents.


    Some explanation:

    The length of the string to be extracted by SUBSTR is calcluated from the difference between the occurrence of the nth and the (n + 1)th delimiter character (- in this case). Note that the (n + 1)th delimiter position is calculated from THESTRING plus an extra delimiter attached to its end to account for the case when we look for the last column and THESTRING does not end in a delimiter.

提交回复
热议问题