How can I tell if a VARCHAR variable contains a substring?

Yatrix picture Yatrix · Sep 4, 2012 · Viewed 160.4k times · Source

I thought it was CONTAINS, but that's not working for me.

I'm looking to do this:

IF CONTAINS(@stringVar, 'thisstring')
   ...

I have to run one select or another, depending on whether that variable contains a string and I can't figure out how to get it to work. All the examples I'm seeing are using columns in the contains.

Thanks in advance.

Answer

Gordon Linoff picture Gordon Linoff · Sep 4, 2012

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'