CLR 整合允許利用 .NET Framework 類庫豐富功能解決資料庫程式問題。以規則運算式驗證為例,展示 CLR 如何增強驗證與過濾能力。
using System;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
public partial class StringFunctions
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static bool RegExMatch(string pattern, string matchString)
{
Regex r1 = new Regex(pattern.TrimEnd(null));
return r1.Match(matchString.TrimEnd(null)).Success;
}
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlString ExtractAreaCode(string matchString)
{
Regex r1 = new Regex(@"\((?[1-9][0-9][0-9])\)");
Match m = r1.Match(matchString);
if (m.Success)
return m.Groups["area"].Value;
else return SqlString.Null;
}
}
假設上述方法已註冊為使用者定義函數(含 RETURNS NULL ON NULL INPUT 選項),可在資料表欄位定義 CHECK 約束:
CREATE TABLE Contacts(
FirstName nvarchar(30),
LastName nvarchar(30),
EmailAddress nvarchar(30) CHECK
(dbo.RegExMatch('[a-zA-Z0-9_-]+@([a-zA-Z0-9_-]+.)+(com|org|edu)', EmailAddress) = 1),
USPhoneNo nvarchar(30) CHECK
(dbo.RegExMatch('([1-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]', USPhoneNo) = 1),
AreaCode AS dbo.ExtractAreaCode(USPhoneNo) PERSISTED
)
AreaCode 為計算欄位,從電話號碼擷取區碼並持久化,可建立索引加速依區碼查詢。此例展示如何用 .NET 類庫擴充 T-SQL 內建函數庫,實現難以用 T-SQL 表達的實用功能。