Given this XML:
<Documents>
<Batch BatchID = "1" BatchName = "Fred Flintstone">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
<Document DocumentID = "299" KeyData = "" ImageFile="Test.TIF" />
</DocCollection>
</Batch>
<Batch BatchID = "2" BatchName = "Barney Rubble">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
</DocCollection>
</Batch>
</Documents>
I need to insert it into a table in SQL Server in this format:
BatchID BatchName DocumentID
1 Fred Flintstone 269
1 Fred Flintstone 6
1 Fred Flintstone 299
2 Barney Rubble 269
2 Barney Rubble 6
This SQL:
SELECT
XTbl.XCol.value('./@BatchID','int') AS BatchID,
XTbl.XCol.value('./@BatchName','varchar(100)') AS BatchName,
XTbl.XCol.value('DocCollection[1]/DocumentID[1]','int') AS DocumentID
FROM @Data.nodes('/Documents/Batch') AS XTbl(XCol)
gets me this result:
BatchID BatchName DocumentID
1 Fred Flintstone NULL
2 Barney Rubble NULL
What am I doing wrong?
Also, can someone recommend a good tutorial for XML in SQL Server?
Thanks
Carl
You were close.
Using a wildcard and a CROSS APPLY, you can generate multiple records.
Changed alias to lvl1 and lvl2 to better illustrate.
Declare @XML xml = '
<Documents>
<Batch BatchID = "1" BatchName = "Fred Flintstone">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
<Document DocumentID = "299" KeyData = "" ImageFile="Test.TIF" />
</DocCollection>
</Batch>
<Batch BatchID = "2" BatchName = "Barney Rubble">
<DocCollection>
<Document DocumentID = "269" KeyData = "" />
<Document DocumentID = "6" KeyData = "" />
</DocCollection>
</Batch>
</Documents>
'
Select BatchID = lvl1.n.value('@BatchID','int')
,BatchName = lvl1.n.value('@BatchName','varchar(50)')
,DocumentID = lvl2.n.value('@DocumentID','int')
From @XML.nodes('Documents/Batch') lvl1(n)
Cross Apply lvl1.n.nodes('DocCollection/Document') lvl2(n)
Returns
BatchID BatchName DocumentID
1 Fred Flintstone 269
1 Fred Flintstone 6
1 Fred Flintstone 299
2 Barney Rubble 269
2 Barney Rubble 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With