Inserting XML into a SQL Server Table
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 on 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?
thank
Charles
+3
source to share
1 answer
You were close.
By using wildcard and CROSS APPLY you can create multiple records.
Changed the lvl1 and lvl2 alias 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
+6
source to share