Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 147
  • Last Modified:

Update/INSERT data based on an XML?

I have had some help in a previous question regarding how to update a table from an XML document.  The code is below.

It updates the ddt_value column given the documentid and ddt_name of the row.

However i have discovered that i also need to insert new rows if the updated row does not exist.

So if there is not a row for the documentId and ddt_Fieldname combination in the table i need to insert a new row with the documentid, ddt_Fieldname and the ddt_value.

Does this require me to traverse the xml document or can the existing sql be extended?

      with Data
      as ( select
	         TestForm1.value('Id[1]', 'INT') AS ID ,
             KeyValue.value('local-name(.)', 'NVARCHAR(255)') AS [Key] ,
             KeyValue.value('.', 'NVARCHAR(255)') AS [Value]
           from  @XmlData.nodes('/BRUM-registret/FormidableTest') A ( TestForm1 )
           cross apply TestForm1.nodes('*[local-name()!="Id"]') B ( KeyValue )
             )
      update  DD
        set ddt_FieldValue = D.[Value]
        from DocumentData DD 
		  inner join Data D on DD.DocumentId = D.ID and DD.ddt_FieldName = D.[Key];

Open in new window


The xml looks like this:

<BRUM-registret><FormidableTest><Id>11</Id><RegisteringUnitId>1</RegisteringUnitId><PersonId>1311</PersonId><PersonIdentity>199107153562</PersonIdentity><UpdateUserId>1</UpdateUserId><CreateDateTime>2014-10-01 11:02:07</CreateDateTime><UpdateDateTime>10/01/2014 11:05:46</UpdateDateTime><Approved>false</Approved><ApprovedDateTime/><ApprovedUserId/><Namn>5567</Namn><Alder>awd</Alder></FormidableTest></BRUM-registret>

Open in new window

0
soozh
Asked:
soozh
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
please check the MERGE statement to update or insert as needed:
http://msdn.microsoft.com/en-us/library/bb510625.aspx
0

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Tackle projects and never again get stuck behind a technical roadblock.
Join Now