문제

We have a SQL Server 2008 Database table: Companies

Company names can be complex like St. Charles Ltd / Hospice Center

If the name provided meets both criteria:

  • consists of 3 or more words
  • at least three words are 4 characters are longer

Then the name will get cleansed, and passed to my SQL SP.

Cleansing the name involves removing non-alpha characters, and also abbreviations such as INC,CORP,LTD,LLC,CO,etc..

Using the example above, my SP would then receive: Charles Hospice Center

My Goal is to use SQL to return any records that match

Charles Center
Center Hospice
Hospice Charles
Charles Hospice
Hospice Center

I could manually split each word out.....

WHERE Name like '%Charles%Center%' or 
      Name like '%Center%Charles%' or
      Name like '%Hospice%Charles%' 
   etc.. etc.. etc..

But if 4 words are provided, then I'm writing out 24 combinations... and thought there might be an easier method, or even a SQL function already available for something like this?


** EDIT **

Full Text Search (from some online reading) appears to a great solutions. I'm just not certain of how to specify 2 of X words must match... or really how to use it correctly. Examples would be great!

도움이 되었습니까?

해결책

You can use string function like

where (CHARINDEX('Charles', Name) > 0 and CHARINDEX('Center', Name) > 0)
OR
(CHARINDEX('Hospice', Name) > 0 and CHARINDEX('Center', Name) > 0)
OR
(CHARINDEX('Hospice', Name) > 0 and CHARINDEX('Charles', Name) > 0)

(OR)

As suggested by @gordon you can use Fulltext search.

Use CONTAINS (Transact-SQL) like

where contains(Name,' Charles AND Center ')
OR
contains(Name,' Charles AND Hospice ')
OR
contains(Name,' Hospice AND Center ')

(OR)

Use FREETEXT (Transact-SQL) like

where FREETEXT(Name,' "Charles and Center')
    OR
    FREETEXT(Name,' Charles AND Hospice ')
    OR
    FREETEXT(Name,' Hospice AND Center ')

In both cases of contains and freetext it assumes your Name column is full-text indexed.

Hope this helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top