SQL Server 2005 整合 .NET CLR,使資料庫引擎成為 .NET 程式碼的宿主環境,開發人員可使用 C#/VB.NET 撰寫預存程序、函數、觸發器、聚合與 UDT。本文將引導完成環境啟用、專案建立、資料庫連結設定,並實作第一個純量函數。
在 SSMS 查詢編輯器執行:
EXEC sp_configure 'clr enabled'; -- 查看狀態
EXEC sp_configure 'clr enabled', 1; -- 啟用 CLR
RECONFIGURE WITH OVERRIDE; -- 套用變更



專案右鍵 → 加入新項目,可選擇:使用者定義型別、預存程序、使用者定義函數、聚合、觸發器。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString TestFunction(string input)
{
return "hello," + input;
}
}
SELECT [dbo].[TestFunction] ('david fan');

掌握基礎流程後,可依序深入: