Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 11.0.1 (中文) » SQL Anywhere 服务器 - SQL 的用法 » 数据库中的 XML » 在数据库中使用 XML » 使用 SQL/XML 以 XML 形式获取查询结果

 

使用 XMLGEN 函数

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

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

  • {$ID}   使用 SalesOrders 表的 ID 列中的值为 <ID> 元素生成内容。

  • {$OrderDate}   使用 SalesOrders 表的 OrderDate 列中的值为 <date> 元素生成内容。

  • {$Customers}   使用 Customers 表的 CompanyName 列中的值为 <customer> 元素生成内容。

SELECT XMLGEN ( '<order>
              <ID>{$ID}</ID>
              <date>{$OrderDate}</date>
              <customer>{$Customers}</customer>
              </order>',
              SalesOrders.ID,
              SalesOrders.OrderDate,
              Customers.CompanyName AS Customers 
              ) AS order_info      
FROM SalesOrders JOIN Customers
ON Customers.ID = SalesOrders.CustomerID
ORDER BY SalesOrders.CustomerID;

此查询会生成以下结果:

order_info
<order>
 <ID>2001</ID>
 <date>2000-03-16</date>
 <customer>The Power Group</customer>
</order>
<order>
 <ID>2005</ID>
 <date>2001-03-26</date>
 <customer>The Power Group</customer>
</order>
<order>
 <ID>2125</ID>
 <date>2001-06-24</date>
 <customer>The Power Group</customer>
</order>
<order>
 <ID>2206</ID>
 <date>2000-04-16</date>
 <customer>The Power Group</customer>
</order>
...
生成属性

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

SELECT XMLGEN ( '<order ID="{$ID}">
                 <date>{$OrderDate}</date>
                 <customer>{$Customers}</customer>
                 </order>',
                SalesOrders.ID,
                SalesOrders.OrderDate,
                Customers.CompanyName AS Customers
              ) AS order_info 
FROM SalesOrders JOIN Customers
ON Customers.ID = SalesOrders.CustomerID
ORDER BY SalesOrders.OrderDate;

此查询会生成以下结果:

order_info
<order ID="2131">
 <date>2000-01-02</date>
 <customer>BoSox Club</customer>
</order>
<order ID="2065">
 <date>2000-01-03</date>
 <customer>Bloomfield&apos;s</customer>
</order>
<order ID="2126">
 <date>2000-01-03</date>
 <customer>Leisure Time</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 文档的标头信息

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

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

这会生成以下结果:

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

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