sp_get_query_template (Transact-SQL)

適用於:SQL Server

傳回查詢的參數化形式。 傳回的結果會模擬使用強制參數化所產生的查詢參數化形式。 sp_get_query_template主要是當您建立 TEMPLATE 計劃指南時使用。

Transact-SQL 語法慣例

語法

  
sp_get_query_template  
   [ @querytext = ] N'query_text'  
   , @templatetext OUTPUT   
   , @parameters OUTPUT   

引數

' query_text '
這是要為其產生參數化版本的查詢。 ' query_text ' 必須以單引號括住,且前面必須加上 N Unicode 規範。 N'query_text ' 是指派給 @querytext 參數的值。 這是 Nvarchar(max) 類型

@templatetext
這是 Nvarchar(max)類型的 輸出參數,提供如指示,以接收參數化形式的 字串常值query_text

@parameters
這是 Nvarchar(max) 類型的 輸出參數,提供如指示,以接收參數名稱和已在 中參數化之資料類型的 @templatetext 字串常值。

備註

sp_get_query_template發生下列情況時傳回錯誤:

  • 它不會參數化query_text 中的任何 常值。

  • query_text為 Null,不是 Unicode 字串、語法無效或無法編譯。

如果sp_get_query_template傳回錯誤,則不會修改 和 @parameters 輸出參數的值 @templatetext 。

權限

需要公用資料庫角色的成員資格。

範例

下列範例會傳回包含兩個常值之查詢的參數化形式。

USE AdventureWorks2022;  
GO  
DECLARE @my_templatetext nvarchar(max)  
DECLARE @my_parameters nvarchar(max)  
EXEC sp_get_query_template   
    N'SELECT pi.ProductID, SUM(pi.Quantity) AS Total  
        FROM Production.ProductModel pm   
        INNER JOIN Production.ProductInventory pi  
        ON pm.ProductModelID = pi.ProductID  
        WHERE pi.ProductID = 2  
        GROUP BY pi.ProductID, pi.Quantity  
        HAVING SUM(pi.Quantity) > 400',  
@my_templatetext OUTPUT,  
@my_parameters OUTPUT;  
SELECT @my_templatetext;  
SELECT @my_parameters;  

以下是參數的參數 @my_templatetext``OUTPUT 化結果:

select pi . ProductID , SUM ( pi . Quantity ) as Total

from Production . ProductModel pm

inner join Production . ProductInventory pi

on pm . ProductModelID = pi . ProductID

where pi . ProductID = @0

group by pi . ProductID , pi . Quantity

having SUM ( pi . Quantity ) > 400

請注意,第一個常數常值 2 會轉換成 參數。 第二個 HAVING 常值 400 , 不會轉換,因為它位於 子句內。 當 ALTER DATABASE 的 PARAMETERIZATION 選項設定為 FORCED 時,sp_get_query_template模擬查詢的參數化格式所傳回的結果。

以下是參數的參數 @my_parameters OUTPUT 化結果:

@0 int  

注意

sp_get_query_template輸出中參數的順序和命名可能會變更 SQL Server 的快速修正工程、Service Pack 和版本升級。 升級也會讓同一個查詢將一組不同的常值參數化,並在兩個輸出參數的結果中套用不同的間距。

另請參閱

系統預存程序 (Transact-SQL)
Database Engine 預存程式 (Transact-SQL)
使用計畫指南指定查詢參數化行為