首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

SQL Server 2005 CLR 函數實作:URL 編碼/解碼

     編輯:關於SqlServer

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

實作步驟 (Visual Studio 2005 + SQL Server 專案)

  1. 建立「SQL Server 專案」,設定目標資料庫連線。
  2. 專案屬性 - 資料庫參考
  3. 新增「使用者定義函數」類別:
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));
    }
}
  1. 建置專案 → 偵錯/部署至目標資料庫。
  2. SSMS 驗證:SELECT dbo.UrlEncode(N'歡迎學習 SQL CLR!')、SELECT dbo.UrlDecode('%E6%AD%A1%E8%BF%8E%E5%AD%B8%E7%BF%92...')。

關鍵設定

  • 資料庫啟用 CLR:sp_configure 'clr enabled', 1; RECONFIGURE;
  • 組件權限集:SAFE (僅 managed 程式碼) 或 EXTERNAL_ACCESS (需 System.Web 組件簽署/信任)。
  • IsDeterministic=true 允許查詢最佳化器快取結果。

應用場景

  • 資料庫層直接編碼/解碼 URL 參數,減少應用層往返。
  • ETL 處理含 URL 參數的日誌資料。
  • 報表產生超連結欄位。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved