Question

I have a input variable

@inputData varchar(Max)

e.g :

Victor:2;John:22;Jo:100

how can I split the variable into two columns?

Col1    Col2
----------
Victor   2
John     22
Jo       100
Was it helpful?

Solution

Here is the script, this gives multiple columns and rows from single string value.

declare @inputData varchar(Max) = 'Victor:2;John:22;Jo:100' +  ';'

;with row(c1,c2)
as
(
SELECT  LEFT
        ( @inputData
         , CHARINDEX(';', @inputData, 0) - 1
        ) col1

        , SUBSTRING 
        ( @inputData
         , CHARINDEX(';', @inputData, 0) + 1
         , LEN(@inputData)  
        ) col2

UNION ALL

SELECT  LEFT
        ( c2
         , CHARINDEX(';', c2, 0) - 1
        ) col1

        , SUBSTRING 
        ( c2
         , CHARINDEX(';', c2, 0) + 1
         , LEN(c2)  
        ) col2 
FROM row 
WHERE CHARINDEX(';', c2, 0) >0
) 

select LEFT(C1, CHARINDEX(':', c1, 0) - 1) col1,  SUBSTRING( c1 , CHARINDEX(':', c1, 0) + 1, LEN(c1)) col2 from row

Output :

col1    col2
Victor  2
John    22
Jo  100

OTHER TIPS

May not be a very good/efficient solution and typically based on your example; you can try the below:

create table tab1(col varchar(100))

insert into tab1 values ('key1:val1;key2:val2;key3:valu3')

Query:

select SUBSTRING((SUBSTRING((left(col,CHARINDEX(';',Col))),0,
charindex(';',col))),0,charindex(':',col)) as Name,

SUBSTRING((SUBSTRING((left(col,CHARINDEX(';',Col))),0,
charindex(';',col))),(charindex(':',col)+1),4) as Age
from tab1 

union

select SUBSTRING((SUBSTRING(right(col,CHARINDEX(';',Col)),0,
charindex(';',col))) ,0,charindex(':',col)) as Name,

SUBSTRING((SUBSTRING(right(col,CHARINDEX(';',Col)),0,
charindex(';',col))),(charindex(':',col)+1),4) as Age
from tab1 

union

select SUBSTRING((SUBSTRING(substring(col,(CHARINDEX(';',Col) + 
1),10),0,charindex(';',col))),0,charindex(':',col)) as Name,

SUBSTRING((SUBSTRING(substring(col,(CHARINDEX(';',Col) + 1),10),0,
charindex(';',col))),(charindex(':',col)+1),4) as Age
from tab1

The best way to achieve this would be UDF (user Defined Functions). This is just a example and you may like to take it further from here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top