sql server 相似度对比

转载自:http://www.dotblogs.com.tw/rachen/archive/2008/10/07/5611.aspx

函数一:产生like对比用字符串

 1 create function fn_get_fuzzy_str( @instr nvarchar(256) )
 2 returns nvarchar(513)
 3 as begin
 4     /*依據傳入字串補上%符號*/
 5     /*
 6     declare @instr nvarchar(256);
 7     set @instr = N'樹林國民小學'; */
 8 
 9     declare @outstr nvarchar(513)
10     
11     if isnull(@instr,'') = '' begin
12   set @outstr = '';
13     end else begin
14   declare @i int;
15   set @i = 1;    
16   set @outstr = '%';
17   while @i <= len(@instr) begin
18       set @outstr = @outstr + substring(@instr,@i,1) + '%';
19       set @i = @i + 1;
20   end
21     end
22     return @outstr;
23 end

函数二:查询函数

create function fn_str_fuzzy_qry( @src_str nvarchar(256) , @match_str nvarchar(256) , @setp int  )
returns int
as begin
    /*字串相似度比對 結果直越大相似度越高*/
    /*
    declare @src_str nvarchar(256); --比對來源
    declare @match_str nvarchar(256); --比對字串
    declare @setp int;    --每次步減幾個字
    */
    declare @fuzzy_str nvarchar(513);
    declare @like_str  nvarchar(513);

    set @fuzzy_str = dbo.fn_get_fuzzy_str(@match_str);

    return case
  when @src_str like @fuzzy_str then
      4000 + 1000 - len(@src_str)
  when ( len(@fuzzy_str) - @setp*2*1 >= 5 ) and @src_str like left(@fuzzy_str,len(@fuzzy_str) - @setp*2*1) then
      3000 + 1000 - len(@src_str)
  when ( len(@fuzzy_str) - @setp*2*2 >= 5 ) and @src_str like left(@fuzzy_str,len(@fuzzy_str) - @setp*2*2) then
      2000 + 1000 - len(@src_str)
  when ( len(@fuzzy_str) - @setp*2*3 >= 5 ) and @src_str like left(@fuzzy_str,len(@fuzzy_str) - @setp*2*3) then
      1000 + 1000 - len(@src_str)
  else 0
    end

end

以上在数据库中执行后,生成两个自定义函数

调用方法

select UserName
from Mytmp01
where
    dbo.fn_str_fuzzy_qry(UserName,N'输入的字符。。。',1) > 0
    Or  dbo.fn_str_fuzzy_qry(N'输入的字符。。。',UserName,1) > 0
order by dbo.fn_str_fuzzy_qry(UserName,N'输入的字符。。。',1) desc

猜你喜欢

转载自www.cnblogs.com/topboy168/p/10491017.html