Use SOUNDEX() word by word on SQL Server

前端 未结 5 1631
青春惊慌失措
青春惊慌失措 2020-12-31 23:59

Here is my problem. For example I have a table Products that contains a field, Name:

Products
ID | Name | ..
1  | \"USB Key 10Go\"
2  | \"I         


        
5条回答
  •  误落风尘
    2021-01-01 00:11

    If you have to do it all in the RDBMS, a UDF would be the best if it's an option.

    Otherwise, you could use this technique to at least soundex the first four words individually using PARSENAME:

    From How do I split a string so I can access item x?:

    PARSENAME(REPLACE('12 inches laptop computer', ' ', '.'), 1)  --return computer
    PARSENAME(REPLACE('12 inches laptop computer', ' ', '.'), 2)  --return laptop
    ...
    

    However: using PARSENAME in this way is a hack and a serious limitation is it only works for a max of 4 parts. If there are 5 or more words PARSENAME will return NULL, so you have to check for that with a conditional and degrade gracefully.

    Here's a simplified example (again, without the NULL checks)

    SELECT *
    FROM Products 
    WHERE SOUNDEX(search_input) = SOUNDEX(PARSENAME(REPLACE(Name, ' ', '.'), 4))
      OR SOUNDEX(search_input) = SOUNDEX(PARSENAME(REPLACE(Name, ' ', '.'), 3))
      OR SOUNDEX(search_input) = SOUNDEX(PARSENAME(REPLACE(Name, ' ', '.'), 2))
      OR SOUNDEX(search_input) = SOUNDEX(PARSENAME(REPLACE(Name, ' ', '.'), 1))
    

提交回复
热议问题