John Livermore
John Livermore

Reputation: 31333

convert sql xml datatype to table

Given the SQL...

declare @xmlDoc xml
set @xmlDoc = '<people>
  <person PersonID="8" LastName="asdf" />
  <person PersonID="26" LastName="rtert" />
  <person PersonID="33" LastName="dfgh" />
  <person PersonID="514" LastName="ukyy" />
</people>'

What would be the sql to convert that xml into a table of two columns PersonID and LastName?

Upvotes: 2

Views: 1830

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 138990

select T.X.value('@PersonID', 'int') as PersonID,
       T.X.value('@LastName', 'nvarchar(50)') as LastName
from @xmlDoc.nodes('/people/person') as T(X)

Upvotes: 2

Stuart Ainsworth
Stuart Ainsworth

Reputation: 12940

SELECT T.c.query('.').value('(//@PersonID)[1]', 'int'),
    T.c.query('.').value('(//@LastName)[1]', 'varchar(50)')
FROM @xmlDoc.nodes('/people/person') T(c)

Upvotes: 2

Related Questions