Blog

Levenshtein Distance in SQL Server

11 January 2005

Merry Christmas, Happy New Year, and all that. This is a kind of dull post but I know some people who come here will find it useful:

I have found an implementation of the Levenshtein distance function in TSQL. This allows you to calculate the similarity between two strings, which is particularly useful for searching features. You will also need a simple user-defined function called MIN3 that is not listed at the above link, here’s the super quick one I wrote:

1   CREATE function Min3( @a int, @b int, @c int ) returns int AS
2   BEGIN
3   	DECLARE @Retval int
4   	if @a <= @b AND @a <= @c
5   		BEGIN
6   		SET @Retval = @a
7   		END
8   	if @b < @a AND @b <= @c
9   		BEGIN
10  		SET @Retval = @b
11  		END
12  	if @c < @a AND @c < @b
13  		BEGIN
14  		SET @Retval = @c
15  		END
16  RETURN @Retval
17  END

Leave a Reply

 

 

 

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>