ASP.NET 內建 Server.UrlEncode/UrlDecode,但在 SQL Server 2000 實作極複雜。SQL Server 2005 CLR 整合讓此需求輕鬆解決。

using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Web; // 需參考 System.Web.dll
public partial class UserDefinedFunctions
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlString UrlEncode(SqlString input)
{
if (input.IsNull) return SqlString.Null;
return new SqlString(HttpUtility.UrlEncode(input.Value));
}
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlString UrlDecode(SqlString input)
{
if (input.IsNull) return SqlString.Null;
return new SqlString(HttpUtility.UrlDecode(input.Value));
}
}
SELECT dbo.UrlEncode(N'歡迎學習 SQL CLR!')、SELECT dbo.UrlDecode('%E6%AD%A1%E8%BF%8E%E5%AD%B8%E7%BF%92...')。sp_configure 'clr enabled', 1; RECONFIGURE;SAFE (僅 managed 程式碼) 或 EXTERNAL_ACCESS (需 System.Web 組件簽署/信任)。IsDeterministic=true 允許查詢最佳化器快取結果。