Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using a function in CONATINS

Status
Not open for further replies.

RobHudson

Programmer
Joined
Apr 30, 2001
Messages
172
Location
GB
Hi

I have a free text index set up on a column in my table. I need to use a SUBSTRING inside the contains but get the following error:

Code:
Msg 102, Level 15, State 1, Line 15
Incorrect syntax near 'SUBSTRING'.

This is an exmaple of the clause:

Code:
AND NOT CONTAINS([mytable].[mycol], SUBSTRING('abcdefghijk', 2, 3))

If I replace the SUBSTRING with a fixed string ('abcd') it works fine.

Are we not able to use functions inside the CONTAINS statement? Or have I done something wrong?

Cheers :)
Rob
 
Can you use variable in CONTAINS clause ?

 
Yes

You have two methods of doing this depending on where your 'abcdefghijk' comes from e.g. if its a passed parameter and only needs changed once then a single substring call into a parameter can do this
e.g.
Code:
declare @v_substringPart varchar(20)
.....
AND NOT CONTAINS ([MyTable].[Col], @v_substringPart )

Alternatively if the value is coming from a field in a table you need to include try

Code:
SELECT * from MyTable myt
INNER JOIN (select substring(MyCol,2,3) as SubStringField from MyTable) myt2 on myt2.KeyField = myt.keyfield
WHERE
....
AND NOT CONTAINS ([MyTable].[Col], SubStringField )

I am not 100% on the second part as I cant ever remember running CONTAINS using a Column from a table.


"I'm living so far beyond my income that we may almost be said to be living apart
 
Thanks hmckillop. It is the 2nd scenario that I need to use where the filter is the column (or SUBSTRING on the column).

Using the INNER JOIN gave a similar error message, I also simplified it by using (and getting the same error):

Code:
SELECT *, SUBSTRING([MyCol], 2, 3) AS SubStringField

Code:
Incorrect syntax near 'SubStringField'.

It seems that only hardcoded strings or variables can be used...
 
Thanks markos :)
It's quite an interesting way of improving my routine. But I still have the underlying problem of not being able to use SUBSTRING inside a CONTAINS. They are using a LIKE and given the vast amount of data I am dealing with LIKE is extremely slow compared to the CONTAINS.
 
Can you compare your current approach (with CONTAINS) with the second solution outlined in that blog?

I would be very interested in the statistics results.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top