如何通过sql查询嵌套xml

时间:2013-03-15 09:27:19

标签: sql-server xml sql-server-2005

我正在尝试生成如下所示的xml:

<caption nr="1000">
    <lang code="EN">Brussels</lang>
    <lang code="FR">Bruxelles</lang>
</caption>
<caption nr="2000">
    <lang code="EN">Antwerp</lang>
    <lang code="FR">Anvers</lang>
</caption>

我在sql数据库中有所有必要的信息,如下所示(sql server 2005):

fld_pcd_cod               fld_pcd_gem             fld_pcd_tal
-------------------------------------------------------------
1000                      Brussels                 EN
1000                      Bruxelles                FR
2000                      Antwerp                  EN
2000                      Anvers                   FR 

我尝试了很多sql查询,包括group by语句,子查询,distintc,......我只是无法绕过它。

这是我能得到的最好的可行解决方案。但这不是我想要的,因为我必须制作新的XSD。

<lang cap="1000" code="FR">BRUXELLES</lang>
<lang cap="1000" code="EN">BRUSSELS</lang>
<lang cap="2000" code="FR">ANVERS</lang>
<lang cap="2000" code="EN">ANTWERP</lang>

这是我用来实现上述xml节点的查询

SELECT fld_pcd_cod as 'lang/@cap', fld_pcd_tal as 'lang/@code', fld_pcd_gem as 'lang'
FROM tbl_pcd
for XML path(''), type

你们有没有人建议如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

caption上获取包含分组的fld_pcd_cod节点,并在相关的子查询中获取lang

select T1.fld_pcd_cod as "@nr",
       (
       select T2.fld_pcd_tal as "@code",
              T2.fld_pcd_gem as "*"
       from tbl_pcd as T2
       where T1.fld_pcd_cod = T2.fld_pcd_cod
       for xml path('lang'), type
       )
from tbl_pcd as T1
group by T1.fld_pcd_cod
for xml path('caption')