Я не полностью проверил это решение, но оно работает для вашего образца данных:
Настройка
Create Table #tbl
(
ID Int,
ShopName VarChar(25),
LocationName VarChar(25)
)
Insert Into #tbl Values
(1,'GreatMall','Great,Mall'),
(2,'Gingermall','Gingermall'),
(3,'MARK.HI','MARK,HI'),
(4,'GALLERY INC','GALLERY. INC')
Запрос
Declare @results As Table (id Int, ShopName VarChar(25), LocationName VarChar(25), mlength Int, charmatches Int)
Declare @sn VarChar(25)
Declare @ln VarChar(25)
Declare @id Int
Declare @cnts Int
Declare @cnt Int
Declare @samechars Int
Declare vCursor Cursor
For Select id, ShopName, LocationName From #tbl
Open vCursor
Fetch Next From vCursor Into @id, @sn, @ln
While @@FETCH_STATUS = 0
Begin
Set @cnts = 1
Set @cnt = 1
Set @samechars = 0
While @cnt <= Case When Len(@sn) > Len(@ln) Then Len(@sn) Else Len(@ln) End
Begin
If Substring(@sn,@cnts,1) = Substring(@ln,@cnt,1)
Begin
Set @cnts = @cnts + 1 --Only move this forward if there is a match
Set @samechars = @samechars + 1
End
Else If Substring(@sn,@cnt,1) = Substring(@ln,@cnt,1) Set @samechars = @samechars + 1
Set @cnt = @cnt + 1
End
Insert Into @results Select @id, @sn As ShopName, @ln As LocationName, Case When Len(@sn) > Len(@ln) Then Len(@sn) Else Len(@ln) End As mlength, @samechars As CharMatches
Fetch Next From vCursor Into @id, @sn, @ln
End
Select *, (Cast(charmatches As Float)/Cast(mlength As Float)) * 100.0 As percentmatch From @results
Close vCursor
DeAllocate vCursor
Drop Table #tbl
Результаты:
id ShopName LocationName mlength charmatches percentmatch
1 GreatMall Great,Mall 10 9 90
2 Gingermall Gingermall 10 10 100
3 MARK.HI MARK,HI 7 6 85.7142857142857
4 GALLERY INC GALLERY. INC 12 11 91.6666666666667