본문 바로가기

Dev_Language/C#.NET

MS-SQL 2005 dll 어셈블리 등록하기

SQL 에서 정규식을 어떻게 사용해야 하는지 검색을 하다 찾은 방법입니다.
MS-SQL 2005 부터는 닷넷 dll을 등록해서 사용할수 있다고 합니다.

출처 : http://jihyunsama.egloos.com/4601342

우선 닷넷에서 dll을 만듭니다.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;

namespace UserRegexFunctions
{
    public partial class UserRegex
    {
        public static SqlString RegexMatch(SqlString pattern, SqlString val)
        {
            if (pattern.IsNull || val.IsNull)
                return SqlString.Null;
            else
            {
                string strRet = "";
                Regex rx = new Regex(pattern.Value, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                MatchCollection matches = rx.Matches(val.Value);
                foreach (Match match in matches)
                {
                    strRet += match.Value;
                }
                return new SqlString(strRet);
            }
        }
    }
}

그리고 해당 dll을 DB 서버로 올린 후

DB 서버에서 아래 쿼리를 실행 시킵니다.

--CLR이 가능하도록 CONFIGURE 를 수정 한다.
SET NOCOUNT ON;
USE MASTER;

ALTER database [MASTER] SET TRUSTWORTHY ON; <- 클러스트링 되어 있는 서버에는 해당 DB에 추가한다.

EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
GO

USE MASTER;
-- DLL을 어셈블리에 등록한다.
CREATE ASSEMBLY UserRegexFunction
FROM 'D:\Project\UserRegexFunctions\UserRegexFunctions\bin\Debug\UserRegexFunctions.dll'
WITH PERMISSION_SET = SAFE;

-- DLL을 사용하는 사용자 정의 함수를 생성한다.
CREATE FUNCTION [dbo].[UserRegexFunction](@Pattern [nvarchar](max), @Val [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [UserRegexFunction].[UserRegexFunctions.UserRegex].[RegexMatch];
GO

// 사용자 정의 함수를 사용하여 정규식을 실행한다.
USE MASTER
SELECT dbo.UserRegexFunction(우하하하하하하(t,b+), '\([^)]*\)')

결과 : 우하하하하하하(t,b+) -> 우하하하하하