很久就想寫總結一下SQL Server解析XML資料的常用方法了,下面就給出一些樣本,有事沒事,你也可以參照著樣本自己動手嘗試著實現一下自己的需求。
樣本1:從XML中解析資料到表變數
DECLARE @ItemMessage XML
DECLARE @ItemTable TABLE(ItemNumber INT PRIMARY KEY,ItemDescription NVARCHAR(300))
SET @ItemMessage=N'<ItemList>
<Item>
<ItemNumber>1</ItemNumber>
<ItemDescription>XBox 360,超值</ItemDescription>
</Item>
<Item>
<ItemNumber>2</ItemNumber>
<ItemDescription>Windows Phone7,快來嘗鮮吧</ItemDescription>
</Item>
</ItemList>'
INSERT INTO @ItemTable
(
ItemNumber,
ItemDescription
)
SELECT T.c.value('(ItemNumber/text())[1]','INT'),
T.c.value('(ItemDescription/text())[1]','NVARCHAR(300)')
FROM @ItemMessage.nodes('/ItemList/Item') AS T(c)
SELECT ItemNumber,
ItemDescription
FROM @ItemTable
運行結果:
樣本二: 解析帶命名空間的XML資料
DECLARE @ItemMessage XML
DECLARE @ItemTable TABLE(ItemNumber INT PRIMARY KEY,ItemDescription NVARCHAR(300))
SET @ItemMessage=N'<ItemList xmlns="http://cd.love.com/SOA">
<Item>
<ItemNumber>1</ItemNumber>
<ItemDescription>XBox 360,超值</ItemDescription>
</Item>
<Item>
<ItemNumber>2</ItemNumber>
<ItemDescription>Windows Phone7,快來嘗鮮吧</ItemDescription>
</Item>
</ItemList>'
;WITH XMLNAMESPACES(DEFAULT 'http://cd.love.com/SOA')
INSERT INTO @ItemTable
(
ItemNumber,
ItemDescription
)
SELECT T.c.value('(ItemNumber/text())[1]','INT'),
T.c.value('(ItemDescription/text())[1]','NVARCHAR(300)')
FROM @ItemMessage.nodes('/ItemList/Item') AS T(c)
SELECT ItemNumber,
ItemDescription
FROM @ItemTable
運行結果: