How to parse nested xml in sql server into single table. Considering RowGuid is unique for each Customer
eg
I want to parse this xml in a single table which would be denormalized and will contain one to many relationships. Considering every nesting has business primary key.
<Customers>
<Customer>
<Type xsi:nil="true" />
<RowGuid>FEFF32BC-1DAB-4F8A-80F0-CFE293C0BEC4</RowGuid>
<AccountId>0</AccountId>
<AccountNumber>bdb8eb51-d</AccountNumber>
<AccountTransactions>
<AccountTransaction>
<PaymentDate>2012-09-13 22:19:58</PaymentDate>
<Balance>500</Balance>
</AccountTransaction>
<AccountTransaction>
<PaymentDate>2012-09-13 22:19:58</PaymentDate>
<Balance>500</Balance>
</AccountTransaction>
</AccountTransactions>
<Addresses>
<Address>
<city>DELHI</city>
</Address>
<Address>
<city>MUMBAI</city>
</Address>
</Addresses>
</Customer>
<Customer>
<Type xsi:nil="true" />
<RowGuid>C3D4772E-1DAB-4F8A-80F0-CFE293C0BEC4</RowGuid>
<AccountId>0</AccountId>
<AccountNumber>bdb8eb51-d</AccountNumber>
<AccountTransactions>
<AccountTransaction>
<PaymentDate>2012-09-13 22:19:58</PaymentDate>
<Balance>500</Balance>
</AccountTransaction>
<AccountTransaction>
<PaymentDate>2012-09-13 22:19:58</PaymentDate>
<Balance>500</Balance>
</AccountTransaction>
</AccountTransactions>
</Customer>
If table doesn’t need to be normalized you can do
LEFT JOIN. I also added a namespace to theCustomerselement, it is needed because ofxsi:nil="true". Try it:UPDATE:
Due to the large query cost of the first version of this query (the one that uses
XMLdata type methods) I created another version that usesOPENXMLinstead ofnodesandvaluemethods. There’s a great difference in cost in favor ofOPENXMLapproach: