Dynamically identify the number of key-value pairs within a string

Viewed 54

I have a requirement to take a pipe delimited string of key-value pairs and to convert the data in columns.

I have a working method I can use however this assumes that the incoming data will be structured identically each time it is delivered and would need updating if a new key-value pair is added and I'd like to future proof it as much as possible.

Here's DDL and sample data and the solution I've worked on so far.

DDL:

    CREATE TABLE #pipers (team_id nvarchar(50), piped_string nvarchar(250))

Sample Data:

    INSERT INTO #pipers (team_id, piped_string) VALUES 
    (newid(), 'team_name:Brighton|stadium:American Express Community Stadium|max_attendance:30750')
    ,(newid(), 'team_name:Middlesbrough|stadium:Riverside|max_attendance:34742')
    ,(newid(), 'team_name:Derby|stadium:Pride Park Stadium|max_attendance:33597')

Current attempt:

    ;WITH xmldata (team_id, piped_string, xml_string)
    AS
    (
    SELECT team_id
        ,piped_string
        ,CAST('<teaminfo>'+'<team>'+REPLACE(piped_string,'|','</team><team>')+'</team>'+'</teaminfo>' AS XML)
    FROM #pipers
    )

    SELECT team_id, 
       piped_string,
       team_name = x.xml_string.value('(/teaminfo/team)[1]','nvarchar(150)'),
       stadium = x.xml_string.value('(/teaminfo/team)[2]','nvarchar(150)'),
       max_attendance = x.xml_string.value('(/teaminfo/team)[3]','nvarchar(150)')
    FROM xmldata x

My question is: how would I go about dynamically identifying the number of pairs within the incoming string and applying that to the XML logic?

1 Answers
Related