SQL“For XML Path” - 具有null类型的多个嵌套结果

时间:2017-03-03 11:22:40

标签: sql-server xml tsql path null

我将为我需要的一个简单示例制作一个块代码

.payload

并使用此代码获取:

reinitializeState: true

但我希望在数字为2时获得c和d并且d元素不显示 (记住这是一个更复杂的查询的例子)

我想要获得:

select      
    (   select
                (Select
                    (Select             
                            NULLIF (t1.number,2) as 'e'
                    FOR XML PATH('d'),type
                    ) 
                FOR XML PATH('c'),type
                ) 
        FOR XML PATH('b1'), type
    ) ,
    t1.number as 'b2'
from
(select 1 as number union all select 2 as number union all select 3 as number) as t1
FOR XML PATH(''), 
ROOT('a')

1 个答案:

答案 0 :(得分:0)

我的神奇晶球告诉我 - 最终 - 你正在寻找这个:

select
    CASE WHEN t1.number<>2 THEN      
    (   select
                (Select
                    (Select             
                            t1.number 'e'
                    FOR XML PATH('d'),type
                    ) 
                FOR XML PATH('c'),type
                ) 
        FOR XML PATH('b1'), type
    ) END,
    t1.number as 'b2'
from
(select 1 as number union all select 2 as number union all select 3 as number) as t1
FOR XML PATH(''), 
ROOT('a')

结果

<a>
  <b1>
    <c>
      <d>
        <e>1</e>
      </d>
    </c>
  </b1>
  <b2>1</b2>
  <b2>2</b2>
  <b1>
    <c>
      <d>
        <e>3</e>
      </d>
    </c>
  </b1>
  <b2>3</b2>
</a>

更新:sedond guess ...

select
    ISNULL(CASE WHEN t1.number<>2 THEN      
    (   select
                (Select
                    (Select             
                            t1.number 'e'
                    FOR XML PATH('d'),type
                    ) 
                FOR XML PATH('c'),type
                ) 
        FOR XML PATH(''), type
    ) END,'') AS b1,
    t1.number as 'b2'
from
(select 1 as number union all select 2 as number union all select 3 as number) as t1
FOR XML PATH(''), 
ROOT('a')

返回

<a>
  <b1>
    <c>
      <d>
        <e>1</e>
      </d>
    </c>
  </b1>
  <b2>1</b2>
  <b1></b1>
  <b2>2</b2>
  <b1>
    <c>
      <d>
        <e>3</e>
      </d>
    </c>
  </b1>
  <b2>3</b2>
</a>