Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL statement to find whole words

Tags:

sql-server

I have a table with a varchar(max) field, and I need to perform text searches on it. Specifically, I need to find whole words. I have tried

Select * From MyTable 
Where Col = @SearchTxt
Or    Col Like @SearchTxt + ' %'
Or    Col Like '% ' + @SearchTxt + ' %'
Or    Col Like '% ' + @SearchTxt

This works to a certain extent, but it does not give me the instances where the SearchTxt is before or after punctuations (like SearchTxt! or SearchTxt,)

Is there a reasonably easy way to get what I'm looking for, without having a whole bunch of where clauses? Also, the column is not indexed, and although speed is not the primary concern, I want the query to run reasonably fast

like image 464
Rama Avatar asked Dec 11 '25 04:12

Rama


1 Answers

You could do something like this:

SELECT <ColumnsList>
FROM MyTable
WHERE Col = @SearchText
OR Col LIKE @SearchTxt + '[^A-Za-z]%'
OR Col LIKE '%[^A-Za-z]' + @SearchTxt + '[^A-Za-z]%'
OR Col LIKE '%[^A-Za-z]' + @SearchTxt

For further reading, Here's Microsoft's documentation on Pattern Matching in Search Conditions

like image 66
Zohar Peled Avatar answered Dec 12 '25 17:12

Zohar Peled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!