position 関数 (XQuery)

現在処理されているアイテムのシーケンス内のコンテキスト アイテムの位置を示す整数値を返します。

構文

fn:position() as xs:integer

説明

SQL Server では、fn:position() を使用できるのは、コンテキストに依存する述語のコンテキスト内のみです。具体的には、角かっこ ([ ]) 内でしか使用できません。この関数との比較を行っても、静的な型の推定中にカーディナリティが減少することはありません。

このトピックでは、AdventureWorks データベースのさまざまな xml 型の列に格納されている XML インスタンスに対して実行する XQuery の例について説明します。これらの各列の概要については、「AdventureWorks データベースの xml データ型表現」を参照してください。

A. position() XQuery 関数を使用して、先頭 2 つの製品特徴を取得する

次のクエリは、先頭 2 製品の機能、つまり <Features> 要素の最初から 2 つの子要素を製品モデル カタログの説明から取得します。3 つ以上特徴がある場合は、<there-is-more/> 要素が結果に追加されます。

SELECT CatalogDescription.query('
     declare namespace pd="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription";
     <Product> 
          { /pd:ProductDescription/@ProductModelID }
          { /pd:ProductDescription/@ProductModelName } 
          {
            for $f in /pd:ProductDescription/pd:Features/*[position()<=2]
            return
            $f 
          }
          {
            if (count(/pd:ProductDescription/pd:Features/*) > 2)
            then <there-is-more/>
            else ()
          } 
     </Product>        
') as x
FROM Production.ProductModel
WHERE CatalogDescription is not null

上のクエリに関して、次の点に注意してください。

  • XQuery プロローグ内の namespace キーワードにより、クエリ本文で使用する名前空間プレフィックスが定義されています。

  • クエリ本文では、ProductModelIDProductModelName が指定された <Product> 要素があり、子要素として返された製品の特徴を保持する XML が構築されます。

  • ここでは position() 関数は、コンテキスト内の <Features> 子要素の位置を特定する述語で使用されています。最初または 2 番目の特徴の場合は、これが返されます。

  • IF ステートメントは、製品カタログに 3 つ以上の特徴があった場合、結果に <there-is-more/> 要素を追加します。

  • カタログの記述がテーブルに保持されていない製品モデルもあるので、WHERE 句を使用して CatalogDescriptions が NULL の行を破棄しています。

結果の一部を次に示します。

<Product ProductModelID="19" ProductModelName="Mountain 100">
  <p1:Warranty xmlns:p1="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain">
    <p1:WarrantyPeriod>3 year</p1:WarrantyPeriod>
    <p1:Description>parts and labor</p1:Description>
  </p1:Warranty>
  <p2:Maintenance xmlns:p2="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain">
    <p2:NoOfYears>10</p2:NoOfYears>
    <p2:Description>maintenance contact available through your dealer or
                    any AdventureWorks retail store.</p2:Description>
  </p2:Maintenance>
  <there-is-more/>
</Product> 
…