1

Does anyone have a idea to matches below 2 situation?

Data:

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

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

I'm using SqlServer2008, and There are 2 user requirements: (1) Find out the spelling is partly different For example: the user enters "ASHRA YUSU", the following is my expected result:

ID| NAMES
2 | ASHRAF MUHAMMAD YUSUF

(2) Find out the name is exactly the same, allow the order is different For example: the user enters "ASHRA YUSU", the following is my expected result:

ID| NAMES
1 | ASHRA MUHAMMAD YUSU
Rahul Neekhra
  • 780
  • 1
  • 9
  • 39
user1625812
  • 187
  • 4

1 Answers1

0

Try this :

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;
DanB
  • 2,022
  • 1
  • 12
  • 24
  • I wait for the day, where people stop posting string splitters with `WHILE` or any other kind of procedural loops... – Shnugo Nov 20 '18 at 10:00
  • Shnugo, what is your solution? – DanB Nov 20 '18 at 14:29
  • Dan, with SQL-Server 2017+ there is `STRING_SPLIT()` (or even better `OPENJSON()`). With former versions there are several approaches using a transformation to XML, recursive CTEs or tally/number tables. There are many answers on SO covering this, [a good overview is this one](https://stackoverflow.com/q/10914576/5089204). Just ignore all approaches with `WHILE`, *multi-statement UDF* or scalar functions... And you might read this [great article serie by Aaron Bertrand](https://sqlperformance.com/2012/07/t-sql-queries/split-strings) – Shnugo Nov 20 '18 at 14:38