T-SQL stored procedure to return google style “suggested” search results

前端 未结 4 1398
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 14:06

Ok, using SQL Server 2008. On my web page I have a textbox with jQuery-UI AutoComplete hooked up.

Now I need a stored procedure to search across all columns of a single

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-03 14:18

    Using the soundex function would be the simplest way to match for similar "items" in several columns. But a better matching algorithm that will be nearly as fast to implement is the Levenshtein Edit Distance. Here is the T-SQL implementation wrapped in a function. Use it to match for similar search terms.

    EDIT Sample of Levenshtien in action (based on gbn's SQL)

    Suppose you named your Levenshtein T-SQL function lvn (just fro brevity's sake) then you could do something like:

    SELECT productname FROM foo WHERE productname 
        LIKE '%myinput%' OR lvn(myinput) < 3
    UNION
    SELECT productnumber FROM foo WHERE productnumber 
        LIKE '%myinput%' OR lvn(myinput) < 3
    UNION
    ...
    
    ORDER BY 1 -- one-based column index sort for UNION queries
    

    Yep. that simple. Btw, i updated the T-SQL levenshtein link to something that makes more sense, and it's an accepted SO answer.

提交回复
热议问题