如何将多个元素值从XML值复制到表中?

时间:2015-08-11 22:46:12

标签: sql-server xml tsql

我有以下脚本,我想填写#rewardscusts表中的 DECLARE @AddOnFeatures AS VARCHAR(1500) DECLARE @AddOnFeaturesXML AS XML SET @AddOnFeatures = '<p1:Addons xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>' SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML) SELECT @AddOnFeaturesXML CREATE TABLE #rewardscusts (AddOnFeature VARCHAR(100) primary key) -- I want to fill AddOnFeatureEnum values in #rewardscusts table please DROP TABLE #rewardscusts 值:

public ActionResult Index()
    {
        return View();
    }

1 个答案:

答案 0 :(得分:1)

这是通过在p1:AddOnFeatureEnum元素上粉碎XML(此部分的引用nodes()方法),然后在碎片元素上使用value()方法来提取{{1值:

varchar(100)

<强> This is full working demo codes :

;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1)
INSERT INTO #rewardscusts
SELECT enum.value('.','varchar(100)')
FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(enum)

输出

DECLARE @AddOnFeatures AS VARCHAR(1500)
DECLARE @AddOnFeaturesXML AS XML

SET @AddOnFeatures = 
'<p1:Addons
xmlns:p1="http://www.alarm.com/WebServices"><p1:AddOnFeatureEnum>WeatherToPanel</p1:AddOnFeatureEnum><p1:AddOnFeatureEnum>EnterpriseNotices</p1:AddOnFeatureEnum></p1:Addons>'

SET @AddOnFeaturesXML = CAST(@AddOnFeatures AS XML)

DECLARE @rewardscusts TABLE(AddOnFeature VARCHAR(100) primary key)

;WITH XMLNAMESPACES('http://www.alarm.com/WebServices' as p1)
INSERT INTO @rewardscusts
SELECT x.value('.','varchar(100)')
FROM @AddOnFeaturesXML.nodes('/p1:Addons/p1:AddOnFeatureEnum') as T(x)

SELECT * FROM @rewardscusts