共用方式為


建構函式函數 (XQuery)

U建構函式函數可由指定輸入,建立任何 XSD 內建或使用者自訂的不可部份完成類型。

語法


            TYP($atomicvalue as xdt:anyAtomicType?
            
            ) as TYP?
        

引數

  • $strval
    將要轉換的字串。
  • TYP
    任何內建的 XSD 類型。

備註

基本及衍生的不可部份完成 XSD 類型都可以支援建構函式。但是,不支援包含 xdt:yearMonthDuration and xdt:dayTimeDurationxs:duration 以及 xs:QNamexs:NMTOKENxs:NOTATION 等的子類型。假如使用者自訂的不可部份完成類型是由以下的類型直接或間接衍生,您也可以使用可在相關結構描述中取得的這種類型。

支援的基本類型

以下是支援的基本類型:

  • xs:string
  • xs:boolean
  • xs:decimal
  • xs:float
  • xs:double
  • xs:duration
  • xs:dateTime
  • xs:time
  • xs:date
  • xs:gYearMonth
  • xs:gYear
  • xs:gMonthDay
  • xs:gDay
  • xs:gMonth
  • xs:hexBinary
  • xs:base64Binary
  • xs:anyURI
支援的衍生類型

以下是支援的衍生類型:

  • xs:normalizedString
  • xs:token
  • xs:language
  • xs:Name
  • xs:NCName
  • xs:ID
  • xs:IDREF
  • xs:ENTITY
  • xs:integer
  • xs:nonPositiveInteger
  • xs:negativeInteger
  • xs:long
  • xs:int
  • xs:short
  • xs:byte
  • xs:nonNegativeInteger
  • xs:unsignedLong
  • xs:unsignedInt
  • xs:unsignedShort
  • xs:unsignedByte
  • xs:positiveInteger

SQL Server 也能以下列方式,支援建構函數引動的常數摺疊:

  • 如果引數是字串常值,則將會在編譯期間評估運算式。當該值無法滿足類型條件約束時,就會發生靜態錯誤。
  • 如果引數是其他類型的常值,則將會在編譯期間評估運算式。當該值無法滿足類型條件約束時,就會傳回空白時序。

範例

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

A. 使用 dateTime() XQuery 函數擷取較舊的產品描述

在此範例中,首先對 XML 範例文件指派 xml 類型變數。此文件包含三個範例 <ProductDescription> 元素,而每個元素都包含一個 <DateCreated> 子元素。

然後查詢該變數,只擷取在特定日期之前建立的那些產品描述。查詢會使用 xs:dateTime() 建構函式函數以鍵入日期,以供比較用。

declare @x xml
set @x = '<root>
<ProductDescription ProductID="1" >
  <DateCreated DateValue="2000-01-01T00:00:00Z" />
  <Summary>Some Summary description</Summary>
</ProductDescription>
<ProductDescription  ProductID="2" >
  <DateCreated DateValue="2001-01-01T00:00:00Z" />
  <Summary>Some Summary description</Summary>
</ProductDescription>
<ProductDescription ProductID="3" >
  <DateCreated DateValue="2002-01-01T00:00:00Z" />
  <Summary>Some Summary description</Summary>
</ProductDescription>
</root>'

select @x.query('
     for $PD in  /root/ProductDescription
     where xs:dateTime(data( ($PD/DateCreated/@DateValue)[1] )) < xs:dateTime("2001-01-01T00:00:00Z")
     return
        element Product
       { 
        ( attribute ProductID { data($PD/@ProductID ) },
        attribute DateCreated { data( ($PD/DateCreated/@DateValue)[1] ) } )
        }
 ')

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

  • FOR ... WHERE 迴圈結構是用以擷取可滿足 WHERE 子句指定之條件的 <ProductDescription> 元素。
  • dateTime() 建構函式函數是用以建構 dateTime 類型值,如此才能適當地進行比較。
  • 然後查詢會建構產生的 XML。因為您正在建構一連串的屬性,所以 XML 建構中會使用逗號及括號。

以下是結果:

<Product 
   ProductID="1" 
   DateCreated="2000-01-01T00:00:00Z"/>

請參閱

參考

對 XML 資料類型進行 XQuery 函數

概念

XML 建構 (XQuery)

說明及資訊

取得 SQL Server 2005 協助