Share via


count 函數 (XQuery)

傳回 $arg 指定時序中所包含的項目號碼。

語法

fn:count($arg as item()*) as xs:integer

引數

  • $arg
    要計數的項目

備註

如果 $arg 是空白時序,就會傳回 0。

範例

本主題是針對 XML 執行個體提供 XQuery 範例,這些執行個體是儲存在 AdventureWorks 資料庫的數個 xml 類型資料行中。如需這些資料行中每個資料行的概觀,請參閱<在 AdventureWorks 資料庫中的 xml 資料類型表示法>。

A. 使用 count() XQuery 函數計數在製造產品型號時工作中心的位置數目

下列查詢計數在製造產品型號的過程中 (ProductModelID=7) 工作中心的位置數目。

SELECT Production.ProductModel.ProductModelID, 
       Production.ProductModel.Name, 
       Instructions.query('
declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";
       <NoOfWorkStations>
          { count(/AWMI:root/AWMI:Location) }
       </NoOfWorkStations>
') as WorkCtrCount
FROM Production.ProductModel
WHERE Production.ProductModel.ProductModelID=7

請注意下列項目是從上一個查詢而來:

  • XQuery 初構中的 namespace 關鍵字定義了命名空間前置詞。 之後會在 XQuery 主體中使用前置詞。

  • 該查詢建構包含 <NoOfWorkStations> 元素的 XML。

  • 在 XQuery 主題中的 count() 函數將計數 <Location> 元素的數目。

以下是結果:

ProductModelID   Name                 WorkCtrCount     
-------------- ---------------------------------------------------
7             HL Touring Frame  <NoOfWorkStations>6</NoOfWorkStations>   

您也可以建構 XML 以包含產品型號識別碼及名稱,如下列查詢所示:

SELECT Instructions.query('
declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";
       <NoOfWorkStations
             ProductModelID= "{ sql:column("Production.ProductModel.ProductModelID") }" 
             ProductModelName = "{ sql:column("Production.ProductModel.Name") }" >
          { count(/AWMI:root/AWMI:Location) }
       </NoOfWorkStations>
') as WorkCtrCount
FROM Production.ProductModel
WHERE Production.ProductModel.ProductModelID= 7

以下是結果:

<NoOfWorkStations ProductModelID="7" 
                  ProductModelName="HL Touring Frame">6</NoOfWorkStations>

除了 XML 之外,您可用非 xml 類型來傳回這些值,如下列查詢所示。 此查詢使用 value() 方法 (xml 資料類型) 來擷取工作中心位置計數。

SELECT  ProductModelID, 
        Name, 
        Instructions.value('declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";
           count(/AWMI:root/AWMI:Location)', 'int' ) as WorkCtrCount
FROM Production.ProductModel
WHERE ProductModelID=7

以下是結果:

ProductModelID    Name            WorkCtrCount
-------------- ---------------------------------
7              HL Touring Frame        6