How to extract data from xml nodes as table from column?

Viewed 708

I have a table in SQL Server with xml column and my goal is to extract whole xml data as table.

Let's say my table looks like this:

CREATE TABLE Archive
(
    [Id] INT IDENTITY,
    [Timestamp] DATETIME,
    [XmlDoc] XML,
    [Description] NVARCHAR(150)
)

The XmlDoc column contains XML data like this:

<Documents>
  <Doc>
    <DocId>11111</DocId>
    <Status>1</Status>
    <DocType>DriverLicense</DocType>
    <ValidDate>2022-12-31</ValidDate>
  </Doc>
  <Doc>
    <DocId>22222</DocId>
    <Status>1</Status>
    <DocType>DriverLicense</DocType>
    <ValidDate>2022-07-16</ValidDate>
  </Doc>
  <Doc>
    <DocId>33333</DocId>
    <Status>2</Status>
    <DocType>DriverLicense</DocType>
    <ValidDate>2018-11-02</ValidDate>
  </Doc>
</Documents>

I need to get table like this:

screenshot

I tried something like

SELECT  
    XmlDoc.value('(/Documents/Doc/DocID)[1]', 'int') as [DocID],
    XmlDoc.value('(/Documents/Doc/Status)[1]', 'int') as [Status],
    XmlDoc.value('(/Documents/Doc/DocType)[1]', 'nvarchar(30)') as [DocType],
    XmlDoc.value('(/Documents/Doc/ValidDate)[1]', 'datetime') as [ValidDate]
FROM
    dbo.Archive

but it returns only first <Doc> node of each xml.

Is it possible to get each Doc node as separate row?

1 Answers

Since nobody answered my question, I find solution by myself. All you need is CROSS APPLY

SELECT 
    a.b.value('(DocId)[1]', 'int') as 'id', 
    a.b.value('(Status)[1]', 'int') as 'Status',
    a.b.value('(DocType)[1]', 'varchar(20)') as 'DocType',
    a.b.value('(ValidDate)[1]', 'varchar(20)') as 'ValidDate' 
FROM 
    dbo.Archive r
    CROSS APPLY r.XmlDoc.nodes('/Documents/Doc') a(b)

Maybe it will help somebody.

Related