2

对此的解决方案正在逃避我,我希望你能提供帮助。

表 [restrictions] 中的数据集如下所示

    item_uid    include    the_value
    00035061     FALSE        'AZ'
    00035061     FALSE        'CA'
    00035061     TRUE         'NC'
    00035061     TRUE         'SC'

预期的 XML 结果应如下所示:

<item>
    <item_uid>00035061</item_uid>
    <restrictions>
        <inclusions>
            <include>NC</include>
            <include>SC</include>
        </inclusions>
        <exclusions>
            <exclude>AZ</exclude>
            <exclude>CA</exclude>
        </exclusions>
    </restrictions>
<item>

我可以分别组装每一面;

SELECT the_value AS 'data()'
FROM restrictions
WHERE include = TRUE AND item_uid = '00031762'
FOR XML PATH ('include'), ROOT ('inclusions')

接着

SELECT the_value AS 'data()'
FROM restrictions
WHERE include = FALSE AND item_uid = '00031762'
FOR XML PATH ('exclude'), ROOT ('exclusions')

但无法弄清楚如何在一条 SQL 语句中生成此 XML。感谢你的协助!

4

1 回答 1

1

您可以将查询作为字段列表中的子查询。

select D.item_uid,
       (
        select R.the_value as 'include'
        from restrictions as R
        where R.include = 1 and R.item_uid = D.item_uid
        for xml path (''), root ('inclusions'), type
       ) as 'restrictions',
       (
        select R.the_value as 'exclude'
        from restrictions as R
        where R.include = 0 and R.item_uid = D.item_uid
        for xml path (''), root ('exclusions'), type
       ) as 'restrictions'
from (select '00035061') as D(item_uid)
for xml path(''),  root('item')

SQL小提琴

type指令使查询返回 XML 而不是文本。
将两个 XML 列命名为 restrictions将使它们最终出现在同一个restrictions元素中,而不是一个。
(select '00035061') as D(item_uid)只是在那里,因此您可以item_uid在一个地方指定您要查找的内容。您可能想用参数替换它。

于 2012-06-09T13:01:13.130 回答