sql:单词分开匹配,发现拼写部分不同

时间:2018-11-20 04:27:00

标签: sql sql-server tsql

有人想匹配以下2种情况吗?

数据:

ID| NAMES
1 | ASHRA MUHAMMAD YUSU
2 | ASHRAF MUHAMMAD YUSUF
3 | YUSUF UTHMAN ABD

====================

我正在使用SqlServer2008,并且 有2个用户要求: (1)找出部分拼写不同的地方 例如:用户输入“ ASHRA YUSU”,以下是我的预期结果:

ID| NAMES
2 | ASHRAF MUHAMMAD YUSUF

(2)找出名称完全相同,允许顺序不同 例如:用户输入“ ASHRA YUSU”,以下是我的预期结果:

ID| NAMES
1 | ASHRA MUHAMMAD YUSU

1 个答案:

答案 0 :(得分:0)

尝试一下:

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END   

go

;with tmp as (select <table>.id, splitdata
        from <table> cross apply dbo.fnSplitString(<table>.name, ' '))
, tmp2 as (select distinct <table>.id, count(*) cnt
        from dbo.fnSplitString(<search string>, ' ') tmp2
        inner join tmp on tmp.splitdata = tmp2.splitData
        group by tmp.id)
  select <table>.*, cnt from <table> inner join tmp2 on <table>.Id = tmp2.Id;