开发者

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

开发者 https://www.devze.com 2023-02-28 01:27 出处:网络
Say I have this XML variable: declare @xml xml=\'< Employee EmployeeId=\"1\" FirstName=\"John\" LastName=\"Smith\" />

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)


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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号