using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Collections; using System.Collections.Generic; public partial class UserDefinedFunctions { /// /// Calculates a similarity ranking value for the two specified strings /// /// [Microsoft.SqlServer.Server.SqlFunction] public static SqlDouble SimilarityRank(string strValue1, string strValue2) { IList pairs1 = WordLetterPairs(strValue1); IList pairs2 = WordLetterPairs(strValue2); int intersection = 0; int union = pairs1.Count + pairs2.Count; foreach(string pair1 in pairs1){ for (int j = 0; j < pairs2.Count; j++) { string pair2 = pairs2[j]; if (pair1.Equals(pair2)) { intersection++; pairs2.RemoveAt(j); break; } } } return new SqlDouble((2.0 * intersection) / union); } /// /// Splits the input into "words" and collects all character pairs /// /// /// private static IList WordLetterPairs(string str) { List allPairs = new List(); // Tokenize the string and put the tokens/words into an array string[] words = str.Split(' ', '\n', '\t'); // For each word foreach (string word in words) foreach (string pairInWord in LetterPairs(word)) allPairs.Add(pairInWord); return allPairs; } /// /// Retrieves all the character pairs in the given string /// /// /// private static string[] LetterPairs(string str) { int numPairs = str.Length - 1; string[] pairs = new string[numPairs]; for (int i = 0; i < numPairs; i++) { pairs[i] = str.Substring(i, 2); } return pairs; } };