Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Contains - only match at start

For some reason I cannot find the answer on Google! But with the SQL contains function how can I tell it to start at the beginning of a string, I.e I am looking for the full-text equivalent to LIKE 'some_term%'.

I know I can use like, but since I already have the full-text index set up, AND the table is expected to have thousands of rows, I would prefer to use Contains.

Thanks!

like image 740
Umair Avatar asked Jul 07 '26 00:07

Umair


2 Answers

You want something like this:

Rather than specify multiple terms, you can use a 'prefix term' if the terms begin with the same characters. To use a prefix term, specify the beginning characters, then add an asterisk (*) wildcard to the end of the term. Enclose the prefix term in double quotes. The following statement returns the same results as the previous one.

-- Search for all terms that begin with 'storm'
SELECT StormID, StormHead, StormBody FROM StormyWeather
WHERE CONTAINS(StormHead, '"storm*"')

http://www.simple-talk.com/sql/learn-sql-server/full-text-indexing-workbench/

like image 89
Johnie Karr Avatar answered Jul 08 '26 16:07

Johnie Karr


You can use CONTAINS with a LIKE subquery for matching only a start:

SELECT * 
FROM (
    SELECT * 
    FROM myTable WHERE CONTAINS('"Alice in wonderland"')
) AS S1 
WHERE S1.edition LIKE 'Alice in wonderland%' 

This way, the slow LIKE query will be run against a smaller set

like image 29
Fernando Fabreti Avatar answered Jul 08 '26 14:07

Fernando Fabreti



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!