2012-03-18 61 views
1

我有一個供應商應用程序的表,它將一些xml數據存儲到類型爲varchar(200)的列中。T-SQL將非結構化XML轉換爲列

表結構和樣本數據是這裏

declare @table table 
(
MerchantID int not null 
,Data  varchar(200) not null) 

insert into @table 
select 1, '<product><productID>1</productID><pdesc>ProductDesc</pdesc></product>' 
union all 
select 2, '<product><itemid>1</itemid><itemname>name of item</itemname></product>' 

有一種方法,以在存儲過程中的原始XML數據轉換成關係格式像下面?

爲e.g時merchantID通過爲1

MerchantID productID pdesc 
    1    1  Product Desc 

MerchantID傳球2輸出應該是

MerchantID itemid itemname 
    2   1  name of item 
+0

這是一個報告,以便存儲過程,需要從XML返回列 – 2012-03-18 14:15:24

回答

0

您可以使用XPath在SQL Server中訪問XML數據節點。

下面是一個使用你的數據的例子。

declare @test xml 
set @test = '<product><productID>1</productID><pdesc>ProductDesc</pdesc></product>' 

SELECT 
@test.value('(/product/productID/node())[1]', 'nvarchar(max)') as productID, 
@test.value('(/product/pdesc/node())[1]', 'nvarchar(max)') as pdesc 

從那裏,你應該能夠像這樣執行你的工會:

SELECT 1, 
xmlfield1.value('(/product/productID/node())[1]', 'int') as id, 
xmlfield1.value('(/product/pdesc/node())[1]', 'nvarchar(max)') as desc 

union 

SELECT 2, 
xmlfield2.value('/product/itemid/node())[1]', 'int') as id, 
xmlfield2.value('/product/itemname/node())[1]', 'nvarchar(max)') as desc 

如果你的數據是在同一列中,你可以使用一個case語句來解決這個問題。

case 
    when merchantId = 1 data.value('(/product/productID/node())[1]', 'int') 
    else data.value('/product/itemid/node())[1]', 'int') 
    end as id 
+0

XML是原材料和非結構化的MERCHANTID三是不同的任何簡單的方法沒有硬編碼XML元素 – 2012-03-18 14:28:22

+0

@SQLLearner轉變 - 有可能是一個動態地做到這一點,而不用硬編碼元素名稱,但這需要一些研究。 – 2012-03-18 16:20:40