Check if a string contains a substring in SQL Server 2005, using a stored procedure

NLV picture NLV · Mar 24, 2010 · Viewed 666.3k times · Source

I've a string, @mainString = 'CATCH ME IF YOU CAN'. I want to check whether the word ME is inside @mainString.

How do I check if a string has a specific substring in SQL?

Answer

Damien_The_Unbeliever picture Damien_The_Unbeliever · Mar 24, 2010

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur