Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何在AS of SELECT FOR XML语句中使用列值_Sql Server_Xml_Tsql_Select - Fatal编程技术网

Sql server 如何在AS of SELECT FOR XML语句中使用列值

Sql server 如何在AS of SELECT FOR XML语句中使用列值,sql-server,xml,tsql,select,Sql Server,Xml,Tsql,Select,我已将此样本减少到绝对必要的最小值。所以我知道,这是没有意义的:-) 我知道,我可以通过以下查询从表中选择XML: select id as [Direction/@Id], direction as [Direction] from devicepdo for xml path('') 结果如下所示: <Direction Id="1">I</Direction> <Direction Id="2">O</Direction>

我已将此样本减少到绝对必要的最小值。所以我知道,这是没有意义的:-)

我知道,我可以通过以下查询从表中选择XML:

select id as [Direction/@Id],
        direction  as [Direction]
from devicepdo
for xml path('')
结果如下所示:

<Direction Id="1">I</Direction>
<Direction Id="2">O</Direction>``
<Direction Id="3">I</Direction>
<Direction Id="4">O</Direction>
....
<In Id="1">I</In>
<Out Id="2">O</Out>``
<In Id="3">I</In>
<Out Id="4">O</Out>
....
I
O``
我
O
....
列方向始终包含I或O,我希望根据列值更改封闭的XML标记

我的结果应该如下所示:

<Direction Id="1">I</Direction>
<Direction Id="2">O</Direction>``
<Direction Id="3">I</Direction>
<Direction Id="4">O</Direction>
....
<In Id="1">I</In>
<Out Id="2">O</Out>``
<In Id="3">I</In>
<Out Id="4">O</Out>
....
I
O``
我
O
....
我尝试在“AS”子句中使用变量或列的所有操作均失败

在我的查询中,“as[Direction/@Id]”中的“Direction”应该是可变的,具体取决于列值


这可能吗?有任何提示或想法吗?

如果所有属性都为空,且内容为空,则不会生成任何标记。根据每行中的值,可以使用此事实生成不同类型的标记

 select 
  -- If direction is I then generate an In tag
  case when direction = 'I' then id else null end as [In/@Id],
  case when direction = 'I' then direction else null end as [In],
  -- If direction is O then generate an Out tag
  case when direction = 'O' then id else null end as [Out/@Id],
  case when direction = 'O' then direction else null end as [Out]
 from devicepdo
 for xml path('')

实际上,所有可能的标记都有表达式,但对于不需要标记类型的行,请使用
case
语句将表达式设为空。

您创建了my day。非常感谢您提供此解决方案!我自己永远也不会发现这一点!