Collection Contents 上一页 下一页 PDF

ASA SQL 用户指南

在数据库中使用 XML

使用 SQL/XML 以 XML 的形式获取查询结果

使用 XMLGEN 函数


XMLGEN 函数用于在 XQuery 构造函数的基础上生成 XML 值。

下面的查询生成的 XML 提供了有关示例数据库中客户订单的信息。它使用以下变量引用:

SELECT XMLGEN ( '<order>
                 <id>{$id}</id>
                 <date>{$order_date}</date>
                 <customer>{$customer}</customer>
                 </order>',
                sales_order.id,
                sales_order.order_date,
                customer.company_name AS customer)
 FROM sales_order JOIN customer
 ON customer.id = sales_order.cust_id

此查询会生成以下结果:

order_info
<order>
 <id>2131</id>
 <date>2000-01-02</date>
 <customer>BoSox Club</customer>
</order>
<order>
 <id>2126</id>
 <date>2000-01-03</date>
 <customer>Leisure Time</customer>
</order>
<order>
 <id>2065</id>
 <date>2000-01-03</date>
 <customer>Bloomfield&apos;s</customer>
</order>
<order>
 <id>2127</id>
 <date>2000-01-06</date>
 <customer>Creative Customs Inc.</customer>
</order>
...
生成属性 

如果您希望订单 ID 号显示为 <order> 元素的属性,要按下面这样编写查询(请注意,变量引用包含在双引号中,因为它指定了一个属性值):

SELECT XMLGEN ( '<order id="{$id}">
                 <date>{$order_date}</date>
                 <customer>{$customer}</customer>
                 </order>',
                sales_order.id,
                sales_order.order_date,
                customer.company_name AS customer
              ) AS order_info
FROM sales_order JOIN customer
 ON customer.id = sales_order.cust_id
 ORDER BY sales_order.order_date

此查询会生成以下结果:

order_info
<order id="2131">
 <date>2000-01-02</date>
 <customer>BoSox Club</customer>
</order>
<order id="2126">
 <date>2000-01-03</date>
 <customer>Leisure Time</customer>
</order>
<order id="2065">
 <date>2000-01-03</date>
 <customer>Bloomfield&apos;s</customer>
</order>
<order id="2127">
 <date>2000-01-06</date>
 <customer>Creative Customs Inc.</customer>
</order>
...

在两个结果集中,客户名 Bloomfield's 都加上了引号,变成了 Bloomfield&apos;s,因为撇号在 XML 中是一个特殊符号,而且从中生成 <customer> 元素的列不是 XML 类型。

有关给 XMLGEN 中的非法字符加引号的详细信息,请参见无效的名称和 SQL/XML

指定 XML 文档的标头信息 

Adaptive Server Anywhere 支持的 FOR XML 子句和 SQL/XML 函数不会在它们生成的 XML 文档中加入版本声明信息。您可以使用 XMLGEN 函数来生成标头信息。

SELECT XMLGEN( '<?xml version="1.0" 
                encoding="ISO-8859-1" ?>
                <r>{$x}</r>',
                (SELECT fname, lname FROM customer FOR XML RAW) AS x )

这样就会产生以下结果:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<r>
 <row fname="Michael" lname="Devlin"/>
 <row fname="Beth" lname="Reiser"/>
 <row fname="Erin" lname="Niedringhaus"/>
 <row fname="Meghan" lname="Mason"/>
 ...
</r>

有关 XMLGEN 函数的详细信息,请参见 XMLGEN 函数 [字符串]


Collection Contents 上一页 下一页 PDF