Parse xml and create and update records in stored procedure

  • I'm passing xml into a stored procedure and I'm updating the records based on a unique record id. This is working fine. What I'm having a problem with is within this xml file the is an array of photos associated with this record id that i need to create records for in another table.

    simplified XML example

    <Record>

    <RecordID>1</RecordID>

    <Quantity>3</Quantity> --I can update the quantity table for this recordid

    <Photos>

    --Could be any number of photos - need to create entry in table for each photo storing recordid recordedo

    </Photos>

    </Record>

    Can somebody point me to an article/example explaining how to acheive this?

    Thanks

    Paul

  • SQL Server's XML handling is pretty good. Basically you'll want to CROSS Apply using the XML.Nodes() method.

    Here's the BOL reference:

    http://msdn.microsoft.com/en-us/library/ms188282.aspx

  • declare @xml xml

    set @xml='<Record>

    <RecordID>1</RecordID>

    <Quantity>3</Quantity> --I can update the quantity table for this recordid

    <Photos>

    --Could be any number of photos - need to create entry in table for each photo storing recordid recordedo

    </Photos>

    </Record>'

    SELECT x.col.value('RecordID[1]', 'INT') AS RecordID,

    x.col.value('Quantity[1]', 'INT') AS Quantity

    FROM @xml.nodes('//Record/Photos') x(col)

    Now u can insert and update the data inside the procedure

  • Hi Srikant

    SELECT x.col.value('RecordID[1]', 'INT') AS RecordID,

    x.col.value('Quantity[1]', 'INT') AS Quantity

    FROM @xml.nodes('//Record/Photos') x(col)

    Will the above not just return me the recordid an quantity?

    I would like to be able to insert the photos into a temporary table for processing so if i had xml with these records:

    --this would have to create 3 records in the temporary table

    recordid 1

    recordid photo 1

    recordid photo 2

    recordid photo 3

    --this would have to create 2 records in the temporary table

    recordid 2

    recordid photo 1

    recordid photo 2

    Thanks

    Paul

  • If you post some sample data that actually represents what you're trying to do e.g. an XML document that looks like the one your referring to with multiple records and photos people are more likely to give you a working sample. Otherwise, read the article I pointed you to.

  • I'll have a look at that, quick glance this seems to be what i'm looking for.

    Thanks Howard

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply