Home Forums Programming XML XML Shred to tabular data RE: XML Shred to tabular data

  • Here is a quick example to shred that xml to a flat table:

    DECLARE @xml XML

    SET @xml = '<employees>

    <employee>

    <emp_id>1</emp_id>

    <emp_name>Bob</emp_name>

    <skills>

    <skills_id>1</skills_id>

    <skills_id>tsql</skills_id>

    <skills_id>2</skills_id>

    <skills_id>SSRS</skills_id>

    <skills_id>3</skills_id>

    <skills_id>SSAS</skills_id>

    <skills_id>4</skills_id>

    <skills_id>SSIS</skills_id>

    <skills_id>5</skills_id>

    <skills_id>Replication</skills_id>

    </skills>

    </employee>

    <employee>

    <emp_id>2</emp_id>

    <emp_name>Frank</emp_name>

    <skills>

    <skills_id>1</skills_id>

    <skills_id>tsql</skills_id>

    <skills_id>2</skills_id>

    <skills_id>SSRS</skills_id>

    <skills_id>3</skills_id>

    <skills_id>SSAS</skills_id>

    </skills>

    </employee>

    </employees>

    '

    SELECT e.c.value('(emp_id)[1]', 'int') AS emp_id

    , e.c.value('(emp_name/text())[1]', 'varchar(50)') AS emp_name

    , s.c.value('(.)[1]', 'varchar(50)') AS skills_id

    FROM @xml.nodes('/employees/employee') e(c)

    CROSS APPLY e.c.nodes('skills/skills_id') AS s(c)

    Not sure if it is going to be what you are after though looking at that data. Did you mean to have the skills id and the skill name in xml nodes of the same name? as by looking at the data i'm guessing you may would like to have it so the skills id is in a column and the skill name is also in a column and both related to each other rather than both in a single column.