Share via


コンテキスト関数 - position (XQuery)

適用対象:SQL Server

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

構文

  
fn:position() as xs:integer  

解説

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

このトピックでは、データベース内のさまざまな xml 型の列に格納されている XML インスタンスに対する XQuery の例を AdventureWorks2022 示します。

A. position() XQuery 関数を使用して最初の 2 つの製品機能を取得する

次のクエリでは、製品モデル カタログの説明から、要素の最初の 2 つの子要素である最初の <Features> 2 つの特徴を取得します。 さらに多くの特徴がある場合は、結果に <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 Prologでキーワード (keyword)名前空間は、クエリ本文で使用される名前空間プレフィックスを定義します。

  • クエリ本文は、ProductModelID 属性と ProductModelName 属性を<持つ Product> 要素を持ち、子要素として返される製品機能を持つ XML を構築します。

  • position() 関数は、コンテキスト内の Features> 子要素の位置を<決定するために述語で使用されます。 1 つ目または 2 番目の機能の場合は、返されます。

  • IF ステートメントは、製品カタログに <2 つ以上のフィーチャーがある場合に、結果に 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>   
...  

参照

xml データ型に対する XQuery 関数