2013-04-01 44 views
0
insert into @res 
    select * from (
     select * from myTable where my_name like '%'[email protected]+'%' 
    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

您可以使用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) 

將覆蓋任何變化,你不再需要這些工會。