以C#寫SQL CLR函數
出自ProgWiki
參照:『維基百科~SQL_CLR』
SQL CLR函數範例(傳單一值)
- 在SQL Server中使用CLR调用.NET方法
- 以C#開啟【類別庫】的專案,編譯成DLL檔後複製到路徑 "C:\Program Files\Microsoft SQL Server"
//#define Use_Regex using System; using System.Collections.Generic; using System.Text; #if (Use_Regex) using System.Text.RegularExpressions; #endif //參考資料 // 在SQL Server中使用CLR调用.NET方法 // http://www.hackercn.net/database/20071218/696.html // 關於關鍵字計算的問題 // http://www.blueshop.com.tw/board/show.asp?subcde=BRD20071123235423KOS&fumcde=FUM20050124192253INM&rplcnt=7 // //尚未使用的參考資料 // EXACT STRING MATCHING ALGORITHMS // http://www-igm.univ-mlv.fr/~lecroq/string/ namespace ClrFunctionsClassLibrary { public class StringFunctionsClass { #if (Use_Regex) //Regex版本 public static int substr_count(string strData, string strKeyWord) { Regex myReg = new Regex(strKeyWord); return myReg.Matches(strData).Count; } #else //string.IndexOf()版本 public static int substr_count(string strData, string strKeyWord) { int index = 0; int count = 0; int KeyWordLength = strKeyWord.Length; while (index != -1) { index = strData.IndexOf(strKeyWord, index); if (index != -1) { index += KeyWordLength; count++; } } return count; } #endif } }
- 開啟SQL Server的CLR設定
EXEC SP_CONFIGURE 'clr enabled',1 RECONFIGURE
- 註冊DLL
CREATE ASSEMBLY asmClrFunctionsClassLibrary FROM 'C:\Program Files\Microsoft SQL Server\ClrFunctionsClassLibrary.dll'
- 連接函數到外部DLL
CREATE FUNCTION dbo.substr_count ( @strData AS NVARCHAR(MAX), @strKeyword AS NVARCHAR(MAX) ) RETURNS INT AS EXTERNAL NAME asmClrFunctionsClassLibrary.[ClrFunctionsClassLibrary.StringFunctionsClass].substr_count
- 使用範例
SELECT [dbo].[substr_count]('《涼宮春日的憂鬱》是輕小說涼宮春日系列原作的校園喜劇風的動畫。','涼宮春日')
SQL CLR傳Table的範例
- 參照: