以下代码在SQL Server中运行
declare @x xml = '<r x="x">
<s a="1" />
<s a="2" />
<s a="deleted" />
</r>
<r x="y">
<s a="3" />
<s a="4" />
<s a="deleted" />
</r>'
select @x.query('
for $r in /r
for $s in $r[s/@a != "deleted"]
let $z := $s (: Need to bring @x from <r> to <s> :)
return
<s>
{$z} (: need to use $z in many places :)
</s>
')
返回
<s>
<r x="x">
<s a="1" />
<s a="2" />
<s a="deleted" />
</r>
</s>
<s>
<r x="y">
<s a="3" />
<s a="4" />
<s a="deleted" />
</r>
</s>
但是,$z
中的预期值应为
<s a="1" x="x" />
<s a="2" x="x" />
<s a="3" x="y" />
<s a="4" x="y" />
我需要实施
需要将flatmap应用于多个XML部分和
编辑:可以使用for $s in $r/s[@a != "deleted"]
x
的最终作业中将<r>
的{{1}}属性带到<s>
。更新 我需要执行SQL Server不支持的以下内容吗?
$z
答案 0 :(得分:0)
declare @x xml = '<r x="x">
<s a="1" />
<s a="2" />
<s a="deleted" />
</r>
<r x="y">
<s a="3" />
<s a="4" />
<s a="deleted" />
</r>';
select @x.query('
<s>
{
for $r in /r
for $s in $r/s[@a != "deleted"] (: Need to delete <s> which @a is "deleted" :)
let $z := $s (: Need to bring @x from <r> to <s> :)
return
<s a="{$z/@a}" x="{$r/@x}" /> (: Some other code need to use $z:)
}
</s>
');
输出:
<s>
<s a="1" x="x" />
<s a="2" x="x" />
<s a="3" x="y" />
<s a="4" x="y" />
</s>