逐步解說:偵錯 SQL CLR 使用者定義的資料表值函式
這個主題適用於:
版本 |
Visual Basic |
C# |
C++ |
Web Developer |
---|---|---|---|---|
Express |
||||
Standard 版 |
||||
Pro/Team 版 |
這個範例將示範如何偵錯 SQL Server Common Language Runtime (SQL CLR) 使用者定義資料表值函式 (UDF)。
當您嘗試偵錯 SQL CLR 物件時,如果出現「已由使用者取消」訊息,就必須手動設定用來執行 Visual Studio 的電腦以及正在執行 SQL Server 的電腦。 如需詳細資訊,請參閱HOW TO:設定您的電腦以啟用 Transact-SQL 和 SQL CLR 偵錯。
注意事項 |
---|
根據您目前使用的設定或版本,您所看到的對話方塊與功能表指令可能會與 [說明] 中描述的不同。 若要變更設定,請從 [工具] 功能表中選取 [匯入和匯出設定]。 如需詳細資訊,請參閱使用設定。 |
若要偵錯 SQL CLR 使用者定義的資料表值函式
在新的 SQL CLR 專案中,建立與資料庫的連接。 如需詳細資訊,請參閱How to: Connect to a Database。
使用下列第一個範例區段中的程式碼來建立新函式,並且將其命名為 TableOfPrimes.cs。 如需詳細資訊,請參閱How to: Develop with the SQL Server Project Type。
藉由將指令碼包含在 SELECT 陳述式中,加入能夠測試函式的指令碼。 在 [方案總管] 中,以滑鼠右鍵按一下 [TestScripts] 目錄,再按 [加入測試指令碼],然後插入下列第二個範例區段中的程式碼。 使用名稱 TestPrime.sql 來儲存檔案。 以滑鼠右鍵按一下這個檔案名稱,再按 [設定為預設偵錯指令碼]。
在 TableOfPrimes.cs 中設定中斷點,然後在 [偵錯] 功能表上按一下 [啟動],對專案進行編譯、部署和單元測試。 當中斷點上出現以黃色箭頭表示的指令指標時,即表示您正在偵錯 SQL CLR 程式碼。
嘗試不同的偵錯功能。
在 [偵錯] 功能表上,重複按 [逐步執行] 觀察函式的逐行執行。
當您逐步執行函式時,可以使用 [區域變數] 和 [監看式] 視窗來觀察不同成員的值。
再按一次 [繼續],以完成此函式的偵錯動作。
在 [輸出] 視窗的 [顯示輸出來源] 下拉式清單中,選取 [資料庫輸出],然後就可以觀察 TestPrimes.sql 指令碼中兩個查詢的執行結果。
範例
以下是讀取事件日誌的程式碼。
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
public partial class UserDefinedFunctions
{
struct primeIndex
{
public int n;
public int p;
public primeIndex(int n, int p)
{
this.n = n; this.p = p;
}
}
static bool isPrime(int p)
{
if (p < 2) return false;
if (p == 2) return true;
if (p % 2 == 0) return false;
for (int d = 3; d * d <= p; d+=2)
{
if (p % d == 0) return false;
}
return true;
}
static int nextPrime(int p)
{
int result = p + 1;
while (!isPrime(result)) result++;
return result;
}
[SqlFunction(FillRowMethodName = "Fill", TableDefinition = "n int,p int,est float")]
public static IEnumerable TableOfPrimes(int n)
{
int p = 1;
for (int i = 1; i <= n; i++)
{
p = nextPrime(p);
yield return new primeIndex(i, p);
}
}
private static void Fill(object source, out int n, out int p, out SqlDouble est)
{
primeIndex pi = (primeIndex)source;
n = pi.n;
p = pi.p;
if (n <5)
est = SqlDouble.Null;
else
{
double log = Math.Log(n);
double loglog = Math.Log(log);
est = n * (log + loglog - 1 + loglog / log - 2 / log);
}
}
}
此為呼叫函式的測試指令碼。
SELECT n,p,est FROM dbo.TableOfPrimes(50)
SELECT TOP 10 n, p, est, est/p AS factor FROM dbo.TableOfPrimes(500) ORDER BY factor DESC
SELECT TOP 10 n, p, est, est/p AS factor FROM dbo.TableOfPrimes(1000) WHERE n>500 ORDER BY factor DESC
請參閱
工作
HOW TO:使用 Common Language Run-time 整合建立和執行 SQL Server 使用者定義函式