forked from ktaranov/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfnWordDifference.sql
51 lines (51 loc) · 1.42 KB
/
fnWordDifference.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
CREATE FUNCTION [dbo].[fnWordDifference] (
@First VarChar(256)
,@Second VarChar(256)
,@Difference TinyInt = NULL
) RETURNS TABLE AS RETURN -- SELECT * FROM dbo.fnWordDifference('012345679012','012456789012',3)
WITH Shift(Position,[Left],[Right],[Difference]) AS (
SELECT 0
,@First
,@Second
,0
WHERE @Difference >= 0 OR @Difference IS NULL
UNION ALL
SELECT Position + 1
,[Left]
,[Right]
,[Difference]
FROM Shift
WHERE Position <= Len([Left] )
AND Position <= Len([Right])
AND SubString([Left] ,Position + 1,1)
= SubString([Right],Position + 1,1)
UNION ALL
SELECT Position
,Convert(VarChar(256),Stuff([Left],Position + 1,1,''))
,[Right]
,[Difference] + 1
FROM Shift
WHERE Position <= Len([Left] )
AND Position <= Len([Right])
AND SubString([Left] + ' ',Position + 1,1)
!= SubString([Right] + ' ',Position + 1,1)
AND([Difference] < @Difference OR @Difference IS NULL)
UNION ALL
SELECT Position
,[Left]
,Convert(VarChar(256),Stuff([Right],Position + 1,1,''))
,[Difference] + 1
FROM Shift
WHERE Position <= Len([Left] )
AND Position <= Len([Right])
AND SubString([Left] + ' ',Position + 1,1)
!= SubString([Right]+ ' ',Position + 1,1)
AND([Difference] < @Difference OR @Difference IS NULL)
) SELECT Top(1)
@First AS [First]
,@Second AS [Second]
,[Left] AS [Root]
,[Difference]
FROM Shift
WHERE [Left] = [Right] AND Position = Len([Left])
ORDER BY [Difference]