【问题标题】:How to use SQL XML and XMLAGG to return multiple xmlelements如何使用 SQL XML 和 XMLAGG 返回多个 xmlelements
【发布时间】:2013-05-23 17:44:02
【问题描述】:

在 SQL 中,我需要创建如下所示的 xml 代码:

    <Phone>
       <PhoneTypeCode tc="12">Mobile</PhoneTypeCode>
       <Area>801</Area>
       <DialNumber>9996666</DialNumber>
    </Phone>
    <Phone>
       <PhoneTypeCode tc="2">Business</PhoneTypeCode>
       <Area>801</Area>
       <DialNumber>1113333</DialNumber>
    </Phone>

使用 xmlagg,但它在 p.desc 之后的 ',' 上抛出错误

这个IBM DB2 SQL函数需要怎么固定才能实现上面的xml?

    select  
      xmlelement(Name "Phone", 
        xmlagg(xmlelement(name "PhoneTypeCode", 
               xmlattributes(trim(p.phtype) as "tc"), trim(p.desc)),
           xmlelement(name "AreaCode", p.area),
           xmlelement(name "DialNumber", p.phone)
            )                   
      ) as xml
    from phone p
    where p.entityid = #entity_id 

我还想补充一点,它确实可以这样编译和运行:

    select  
      xmlelement(Name "Phone", 
        xmlagg(xmlelement(name "PhoneTypeCode", 
               xmlattributes(trim(p.phtype) as "tc"), trim(p.desc))
        )                   
      ) as xml
    from phone p
    where p.entityid = #entity_id 

这是它返回的内容:

    <Phone>
       <PhoneTypeCode tc="12">Mobile</PhoneTypeCode>
       <PhoneTypeCode tc="2">Business</PhoneTypeCode>
    </Phone>

当然,我需要区域和拨号号码。就好像你在一个 xmlagg 中不能有多个 xmlelement。

【问题讨论】:

    标签: db2 sqlxml


    【解决方案1】:

    这个IBM DB2 SQL函数需要如何修复才能实现上面的xml?

    首先,您可能需要计算括号。通常,右括号的数量与左括号的数量一样多。

    其次,您根本不需要 XMLAGG()。当基于多个关系记录将多个相同类型的元素插入单个外部元素时,您会使用它,例如

     <phones>
       <phone no="1" .../>
       <phone no="2" .../>
       ...
     </phones>
    

    对你来说,这样的事情应该可以工作:

      with phone (phtype, desc, area, phone) as 
         (values ('home','blah','555','555-5555'),('office','blah','555','555-1111'))
      select  
        xmlelement(
          Name "Phone", 
          xmlelement(
            name "PhoneTypeCode", 
            xmlattributes(
               trim(p.phtype) as "tc"
            ), 
            trim(p.desc)
          ),
          xmlelement(name "AreaCode", p.area),
          xmlelement(name "DialNumber", p.phone)                   
        ) as xml
      from phone p
    

    【讨论】:

    • 感谢您的浏览。我固定了括号的数量。我还添加了 as "desc" 并得到了这个错误:[SQL0199] Keyword AS not expected。有效标记:),它突出显示了刚刚添加的标记。
    • 我误解了你原来的要求。请查看正确答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2021-07-28
    • 2011-01-03
    • 2017-03-31
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多