在t-sql中添加函数使事情变得更简单

时间:2013-04-01 08:36:18

标签: sql-server tsql

insert into @res
    select * from (
        select * from myTable where my_name like '%'+@token+'%'
    union

        --replace special characters
        select * from myTable where my_name like '%'+REPLACE ( @token , 'e' , 'è' )+'%' order by name
        select * from myTable where my_name like '%'+REPLACE ( @token , 'e' , 'é' )+'%' order by name
        select * from myTable where my_name like '%'+REPLACE ( @token , 'e' , 'Ě' )+'%' order by name
        ----

) as tmp order by name

注释之间的代码部分比这里要长得多。

如何将其移至新功能,而不会失去其功能?

1 个答案:

答案 0 :(得分:1)

您可以将LIKE%ar[e,è,é,Ě]na%这样的字符串一起使用,这将涵盖您的所有工会。如果规则太多,这里还有一个功能:

你去吧

CREATE FUNCTION transform (@inStr varchar(300))
returns varchar(255)
AS  
BEGIN
DECLARE @registry varchar(300),
    @curChar varchar(20),
    @outStr varchar(300),
    @counter int,
    @start int,
    @end int;

SET @outStr = '%';
/* Creating a registry of replacements in format {X}[x,X,Xx];
   Where {X} contains the character to be replaced,
   [x,X,Xx]; contains the replacemet characters
*/
SET @registry = '{e}[e,è,é,Ě];
                 {s}[ ..other translations of "s" go here.. ];
                 {n}[n,N];';

set @counter = 1;

WHILE (LEN(@inStr) >= @counter)
    BEGIN
        SELECT @curChar = substring(@inStr, @counter, 1)
        IF (CHARINDEX( '{' + @curChar + '}', @registry, 1) > 0)
            BEGIN
                SELECT @start = CHARINDEX( '{' + @curChar + '}', @registry, 1) + 2;
                SELECT @end = CHARINDEX( ';', @registry, @start);
                SELECT @curChar = substring(@registry, @start + 1, @end - @start - 1);
            END

        SET @outStr = @outStr + @curChar
        SET @counter = @counter + 1;
    END 
SET @outStr = @outStr + '%'

RETURN @outStr; 
END

例如这里

... WHERE x.str like transform('arena')

该函数将返回%ar[e,è,é,Ě][n,N]a%。 此字符串表示 - 包含以ar开头的字符串的任何值,下一个字符为e,è,é,Ě中的任意一个,n,N中的任何一个字符,以a结尾。

因此...

    select * from myTable where my_name like transform(@token)

将涵盖任何变体,您不再需要这些工会。