C#字符串函数为T-SQL标量函数

时间:2011-07-13 11:22:11

标签: c# sql-server tsql sql-server-2008 user-defined-functions

我想使用c#函数修改html有效url名称的字符串。功能如下:

public static string HTMLValidName(string input)
{
    string[] pattern = new string[] { "[^a-zA-Z0-9-]", "-+" };
    string[] replacements = new string[] { "-", "-" };
    input = input.Trim();
    input = input.Replace("Ç", "C");
    input = input.Replace("ç", "c");
    input = input.Replace("Ğ", "G");
    input = input.Replace("ğ", "g");
    input = input.Replace("Ü", "U");
    input = input.Replace("ü", "u");
    input = input.Replace("Ş", "S");
    input = input.Replace("ş", "s");
    input = input.Replace("İ", "I");
    input = input.Replace("ı", "i");
    input = input.Replace("Ö", "O");
    input = input.Replace("ö", "o");
    for (int i = 0; i <= pattern.Length - 1; i++)
        input = Regex.Replace(input, pattern[i], replacements[i]);

    while(input.Contains("--"))
    {
        input = input.Replace("--", "-");
    }

    if (input[0] == '-') input = input.Substring(1, input.Length - 1);

    return input;
}

我需要将此函数用于SQL结果。像SELECT ID FROM Categories WHERE HTMLValidName(Title)= @ URLTitle

如何将其转换为T-SQL函数,还是可以在c#中创建此函数?

2 个答案:

答案 0 :(得分:3)

CREATE FUNCTION dbo.HtmlValidName(@input nvarchar(max))
    RETURNS nvarchar(max)
AS
BEGIN
    DECLARE @i int
    DECLARE @match int

    -- Remove diacritical marks
    SET @input = CAST(@input AS varchar(max)) COLLATE Japanese_BIN

    -- Replace non-alphanumerics with dash
    SET @i = 0
    WHILE @i < 1000000
    BEGIN
        SET @match = PATINDEX('%[^a-zA-Z0-9-]%', @input)
        IF @match = 0 BREAK
        SET @input = STUFF(@input, @match, 1, '-')
        SET @i = @i + 1
    END

    RETURN @input
END

答案 1 :(得分:2)

您可以创建在SQL服务器中运行的托管用户定义函数,并从外部查看,就像普通的用户定义函数一样。有关详细信息,请参阅here