SQL Server For XML PATH嵌套没有发生

时间:2016-09-26 10:15:30

标签: sql sql-server xml

我正在尝试使用适当的嵌套以所需格式从某个变量生成XML。在启动<SProc>元素之前,我无法关闭<ParamList>元素。请帮我解决这个SQL语句。

我想要的输出是:

<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代码&amp;它的输出是不同的:

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 个答案:

答案 0 :(得分: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将存储过程的名称作为原始元素内容插入,当您希望将其包装在元素中时。