在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>
但当然,我需要Area和DialNumber。就好像你在xmlagg中不能有多个xmlelement。
答案 0 :(得分:0)
如何修复此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