2010-08-04 4 views
1

SQL에서 regex.split를 구현하는 함수를 만들었습니다. 코드는 다음과 같습니다.SQL 서버에 대한 regex split 구현

private static IEnumerable<IndexedValue<T>> ToIndexedValue<T>(IEnumerable<T> list) 
{ 
    int idx = 1; 
    foreach (T value in list) 
    yield return new IndexedValue<T>(++idx, value); 
} 
private struct IndexedValue<T> 
{ 
    public int Index; 
    public T Value; 
    public IndexedValue(int index, T value) 
    { 
    Index = index; 
    Value = value; 
    } 
} 
[SqlFunction(FillRowMethodName = "FillSplit", 
    TableDefinition = "[ID] int, [Value] nvarchar(max)")] 
public static IEnumerable RegexSplit(SqlString input, SqlString pattern) 
{ 
    if (input.IsNull) 
    input = String.Empty; 
    if (pattern.IsNull) 
    pattern = String.Empty; 
    try 
    { 
    return ToIndexedValue<string>(Regex.Split(input.Value, pattern.Value, Options)); 
    } 
    catch 
    { 
    throw; 
    } 
} 
public static void FillSplit(object obj, out int id, out SqlString value) 
{ 
    IndexedValue<string> iv = (IndexedValue<string>)obj; 
    id = iv.Index; 
    value = iv.Value; 
} 

그러나 시도 할 때 id 값은 있지만 텍스트 값은 비어 있습니다. 누군가 도울 수 있습니까?

+0

이 원본을 찾고, 속는 사람입니다. 편집 : 사실은 속마귀,하지만 속는 내 대답은 :) – leppie

답변

0

당신은 (SQL CLR 어셈블리로 컴파일) 이동 :

using System.Collections; 
using System.Text.RegularExpressions; 
using Microsoft.SqlServer.Server; 

public partial class UserDefinedFunctions 
{ 
    [SqlFunction] 
    public static bool RegexMatch(string expr, string regex) 
    { 
    return Regex.IsMatch(expr, regex); 
    } 

    [SqlFunction] 
    public static string RegexReplace(string expr, string regex, string replace) 
    { 
    return Regex.Replace(expr, regex, replace); 
    } 

    [SqlFunction(FillRowMethodName="GetToken", 
     TableDefinition="Value nvarchar(max)")] 
    public static IEnumerable RegexSplit(string expr, string regex) 
    { 
    return Regex.Split(expr, regex); 
    } 

    public static void GetToken(object row, out string str) 
    { 
    str = (string) row; 
    } 
} 

원래부터 : microsoft sql equivalent of mysql REGEXP

0

사용중인 정규 표현식이 빈 문자열 또는 공백 배열을 반환하는 것으로 의심됩니다. 수식 자체에 간단한 명령 줄 테스트 프레임을 설정하려고 시도 했습니까?

Options이 정의되지 않았다는 점을 제외하고는이 코드에 아무런 문제가 없습니다. 이것은 다른 곳에서 정의 된 상수입니까? 여기