如何使用 PL SQL 输出这种 XML 格式
Posted
技术标签:
【中文标题】如何使用 PL SQL 输出这种 XML 格式【英文标题】:How make this XML format output using PL SQL 【发布时间】:2016-02-04 09:34:49 【问题描述】:我想写一个pl sql函数,以以下xml格式返回oracle表数据:
<loans>
<loan>
<id>1</id>
<name>Bank Loan</name>
<description>Bank Loan-1</description>
<amount>25000</amount>
<sanction_date>2016-01-27</sanction_date>
<rate>4.5</rate>
</loan>
<loan>
<id>2</id>
<name>Bank 2</name>
<description>Bank Loan-2</description>
<amount>452500</amount>
<sanction_date>2016-01-27</sanction_date>
<rate>7.67</rate>
</loan>
<loan>
<id>3</id>
<name>New Loan</name>
<description>NY Bank Loan</description>
<amount>1250000</amount>
<sanction_date>2016-01-27
</sanction_date>
<rate>12.25</rate>
</loan>
</loans>
但不是上面的格式,它给了我下面的格式,有许多 loans 标签而不是一个作为父标签:
<loans>
<loan>
<id>1</id>
<name>Bank Loan</name>
<description>Bank Loan-1</description>
<amount>25000</amount>
<sanction_date>2016-01-27</sanction_date>
<rate>4.5</rate>
</loan>
</loans>
<loans>
<loan>
<id>2</id>
<name>Bank 2</name>
<description>Bank Loan-2</description>
<amount>452500</amount>
<sanction_date>2016-01-27</sanction_date>
<rate>7.67</rate>
</loan>
</loans>
<loans>
<loan>
<id>3</id>
<name>New Loan</name>
<description>NY Bank Loan</description>
<amount>1250000</amount>
<sanction_date>2016-01-27
</sanction_date>
<rate>12.25</rate>
</loan>
</loans>
作为初学者,我认为我以错误的方式排列它们。这是我的 PL SQL 代码:
SELECT xmlagg
(
xmlelement("loans",
XMLAGG(
xmlelement("loan",
xmlelement("id", e.LNTYPE_ID),
xmlelement("name", e.LNTYPE_NAME),
xmlelement("description", e.LNTYPE_DESCRIPTION),
xmlelement("amount", e.LNTYPE_AMOUNT),
xmlelement("sanction_date", e.LNTYPE_SANCTION_DATE),
xmlelement("rate", e.LNTYPE_INTEREST_RATE)
)
)
)
)
as clob
FROM TBL_LOAN_TYPE e
group by e.LNTYPE_ID;
【问题讨论】:
【参考方案1】:你很亲密,你只需要摆脱外面的 xmlagg 和 group by:
SELECT xmlelement("loans",
XMLAGG(
xmlelement("loan",
xmlelement("id", e.LNTYPE_ID),
xmlelement("name", e.LNTYPE_NAME),
xmlelement("description", e.LNTYPE_DESCRIPTION),
xmlelement("amount", e.LNTYPE_AMOUNT),
xmlelement("sanction_date", e.LNTYPE_SANCTION_DATE),
xmlelement("rate", e.LNTYPE_INTEREST_RATE)
)
)
) as clob
FROM TBL_LOAN_TYPE e;
编辑:当您在 e.LNTYPE_ID 上使用 group by 时,您实际上会得到三个单独的行,因为 ID 都是唯一的。例如运行这段代码:
SELECT xmlelement("loans",
XMLAGG(
xmlelement("loan",
xmlelement("id", e.LNTYPE_ID),
xmlelement("name", e.LNTYPE_NAME),
xmlelement("description", e.LNTYPE_DESCRIPTION),
xmlelement("amount", e.LNTYPE_AMOUNT),
xmlelement("sanction_date", e.LNTYPE_SANCTION_DATE),
xmlelement("rate", e.LNTYPE_INTEREST_RATE)
)
)
) as clob
FROM TBL_LOAN_TYPE e
GROUP BY e.LNTYPE_ID;
将返回三个独立的 XML 片段,每个贷款一个。然后,外部 XMLAGG 将这些组合成一个 XML 文档,您可以在此处阅读有关 XMLAGG 的更多信息:https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions215.htm
【讨论】:
非常感谢。我一整天都筋疲力尽。请解释一下它是如何工作的,你删除了 group by。 更新了我的答案,希望它有助于解释它以上是关于如何使用 PL SQL 输出这种 XML 格式的主要内容,如果未能解决你的问题,请参考以下文章
如何编写一个 PL/SQL 程序来打印出看起来像 xml 格式的字符串