2017-04-03 92 views
0

我一直在試圖寫這個查詢,但到目前爲止,都無濟於事。基於存儲在SQL Server XML數據中的字符串構建字符串

下面是在SQL Server中的XML列中的某些部分數據:

<DashboardWidgets> 
    <DashboardWidget id="14"> 
     <EnumName>PersonalProgressIndividual</EnumName> 
     <OnOff>1</OnOff> 
     <Movable>0</Movable> 
     <Removable>0</Removable> 
     <SubItemData> 
      <SubItem id="1"> 
       <OnOff>1</OnOff> 
       <Movable>1</Movable> 
       <Removable>1</Removable> 
      </SubItem> 
      <SubItem id="2"> 
       <OnOff>1</OnOff> 
       <Movable>1</Movable> 
       <Removable>1</Removable> 
      </SubItem> 
      <SubItem id="3"> 
       <OnOff>1</OnOff> 
       <Movable>1</Movable> 
       <Removable>1</Removable> 
      </SubItem> 
      <SubItem id="4"> 
       <OnOff>0</OnOff> 
       <Movable>0</Movable> 
       <Removable>0</Removable> 
      </SubItem> 
      <SubItem id="6"> 
       <OnOff>0</OnOff> 
       <Movable>0</Movable> 
       <Removable>0</Removable> 
      </SubItem> 
     </SubItemData> 
    </DashboardWidget> 
</DashboardWidgets> 

我的目標是查詢表和檢索ID和值的格式化字符串。

例如,我需要查詢ID爲14的DashboardWidget節點,並從其中包含的SubItemData子節點構建字符串。

將需要與14號儀表盤小部件的查詢字符串結果:

"1,1,1,1|2,1,1,1|3,1,1,1|4,0,0,0|6,0,0,0" 

我已經能夠通過提取所有的值,但沒有任何分隔符在所有接近。

DECLARE 
    @companyID INT = 23 
    ,@dwID  INT = 14 
; 

DECLARE @xml xml 
SELECT @xml = c.DashboardWidgetSettings FROM dbo.Company c WHERE c.CompanyID = @companyID; 

SELECT 
    x.Rec.query('./SubItem').value('.', 'varchar(max)') AS 'SubItemData' 
FROM @xml.nodes('/DashboardWidgets/DashboardWidget[@id=sql:variable("@dwID")]/SubItemData') as x(Rec) 
; 

任何幫助或點在正確的方向將不勝感激。

回答

1
Declare @XML xml = '<DashboardWidgets><DashboardWidget id="14"><EnumName>PersonalProgressIndividual</EnumName><OnOff>1</OnOff><Movable>0</Movable><Removable>0</Removable><SubItemData><SubItem id="1"><OnOff>1</OnOff><Movable>1</Movable><Removable>1</Removable></SubItem><SubItem id="2"><OnOff>1</OnOff><Movable>1</Movable><Removable>1</Removable></SubItem><SubItem id="3"><OnOff>1</OnOff><Movable>1</Movable><Removable>1</Removable></SubItem><SubItem id="4"><OnOff>0</OnOff><Movable>0</Movable><Removable>0</Removable></SubItem><SubItem id="6"><OnOff>0</OnOff><Movable>0</Movable><Removable>0</Removable></SubItem></SubItemData></DashboardWidget></DashboardWidgets>' 

Select Stuff((Select Distinct '|' +String 
       From (
        Select String = f.n.value('@id','varchar(50)') 
            +',' 
            +f.n.value('(OnOff)[1]','varchar(50)') 
            +',' 
            +f.n.value('(Movable)[1]','varchar(50)') 
            +',' 
            +f.n.value('(Removable)[1]','varchar(50)') 
        From @XML.nodes('DashboardWidgets/DashboardWidget/SubItemData') t(n) 
        Cross Apply t.n.nodes('SubItem ') f(n) 
        ) X 
       For XML Path ('')),1,1,'') 

返回

1,1,1,1|2,1,1,1|3,1,1,1|4,0,0,0|6,0,0,0 
+0

哇!約翰,我不能夠感謝你。這正是我所需要的,完美的作品!乾杯! – webface

+0

@webface高興地幫助:) –