2016-09-26 91 views
2

我想用合適的嵌套生成所需格式的某些變量的XML。在啓動<ParamList>元素之前,我無法關閉<SProc>元素。請幫我解決這個SQL語句。SQL Server for XML PATH嵌套沒有發生

我所需的輸出是:

<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <SProc>dbo.usp_InsertUserPlay</SProc> 
    <ParamList> 
     <Param>Rocky</Param> 
     <Param>Boxer</Param> 
     <Param>SpaceX</Param> 
     <Param xsi:nil="true" /> 
     <Param>0</Param> 
    </ParamList>  
</AsyncRequest> 

我的SQL代碼&其輸出是不同的:

Declare @requestMessage xml, 
     @P1 nvarchar(20) = 'Rocky', 
     @P2 nvarchar(20) = 'Boxer', 
     @P3 nvarchar(20) = 'SpaceX' 

select 
    @requestMessage = (select 'dbo.usp_InsertUserPlay', 
          (select @P1 as [Param], 
            @P2 as [Param],  
            @P3 as [Param], 
            null as [Param],  
            0 as [Param] 
          FOR XML RAW('ParamList'), TYPE, Elements XSINIL) 
         FOR XML PATH ('SProc'), ROOT('AsyncRequest'), TYPE, ELEMENTS XSINIL) 

select @requestMessage AS XML_Output 

輸出是:

<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <SProc>dbo.usp_InsertUserPlay 
     <ParamList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
      <Param>Rocky</Param> 
      <Param>Boxer</Param> 
      <Param>SpaceX</Param> 
      <Param xsi:nil="true" /> 
      <Param>0</Param> 
     </ParamList></SProc> 
</AsyncRequest> 

回答

1

你是非常接近:

select @requestMessage = (select 'dbo.usp_InsertUserPlay' as [SProc], 
       (select @P1 as [Param], 
         @P2 as [Param],  
         @P3 as[Param],         
         null as [Param],  
         0 as [Param] 
        FOR XML RAW('ParamList'), TYPE, Elements XSINIL) 
      FOR XML PATH('AsyncRequest'), TYPE, ELEMENTS XSINIL) 

訣竅是,如果您不提供列名稱,則會導致SQL Server插入存儲過程的名稱作爲原始元素內容,當您希望它包裝在元素中時。