Q:

SQL split a comma delimited string by fixed length

I have a string of comma separated values, I am loading these values into a system that has a max length I need to abide by. Once the string hits a max length it should move the values to another column but retain values. For the sake of this example below, I only need to split the string into two columns.
For example my string value = val1,val2,val3,val4,val5
Max length of output fields = 15
Output should be two columns:
ValueList1             ValueList2
val1,val2,val3         val4,val5

I'm trying to complete this with T-SQL but this is not a common issue I need to solve and am stumped. Any help would be greatly appreciated.

A:

you can try this.
DECLARE @stringvalue VARCHAR(5000) = 'val1,val2,val3,val4,val5'
DECLARE @MaxLengthofOutputFields INT = 15

SELECT 
    CASE WHEN LEN(@stringvalue) > @MaxLengthofOutputFields 
        THEN LEFT(@stringvalue, @MaxLengthofOutputFields - CHARINDEX(',',REVERSE(LEFT(@stringvalue,@MaxLengthofOutputFields)))) 
        ELSE @stringvalue END   , 
    CASE WHEN LEN(@stringvalue) > @MaxLengthofOutputFields THEN 
        SUBSTRING(@stringvalue, @MaxLengthofOutputFields - CHARINDEX(',',REVERSE(LEFT(@stringvalue,@MaxLengthofOutputFields))) + 2, LEN(@stringvalue)) 
        END

Result:
-------------------- -------------
val1,val2,val3       val4,val5

