简体   繁体   中英

SQL Server 2008: How do you convert an XML variable into tabular data?

Say I have this XML variable:

declare @xml xml='< Employee EmployeeId="1" FirstName="John" LastName="Smith" />  
< Employee EmployeeId="2" FirstName="Jack" LastName="Brown" />  
< Employee EmployeeId="3" FirstName="Albert" LastName="Gordon" />  
< Employee EmployeeId="4" FirstName="Kate" LastName="White" />'

And a table with this structure:

EmployeeId (int)  
FirstName varchar(50)  
LastName varchar(50) 

How do you populate it? I'm using SQL Server 2008.

INSERT INTO YourTable
SELECT 
    tab.col.value('@EmployeeId','int'),
    tab.col.value('@FirstName','varchar(50)'),
    tab.col.value('@LastName','varchar(50)')
FROM @xml.nodes('/Employee') as tab(col)

you can do it like this way too

DECLARE @xml XML 
SET @xml = '<root>
  <row>one</row>
  <row>two</row>
  <row>three</row>
</root>'

CREATE TABLE #Fields(Field varchar(MAX))

INSERT INTO #Fields
SELECT 
    x.y.value('text()[1]', 'varchar(5)') 
FROM @xml.nodes('root/row') x(y)

SELECT * FROM #Fields
DROP TABLE #Fields

How do you populate it?

Assuming you mean the table and not the xml.

insert into YourTable (EmployeeID, FirstName, LastName)
select 
  e.value('@EmployeeId', 'int'),
  e.value('@FirstName', 'varchar(50)'),
  e.value('@LastName', 'varchar(50)')
from @xml.nodes('Employee') as n(e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM