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?
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)
REPLACE
called itself; "nested" is when the result of a function call is immediately passed to another function.
select CHARINDEX('ME' collate Latin1_General_CS_AS,'Home')
and select CHARINDEX('ME' collate Latin1_General_CI_AS,'Home')
. (In collations, CS
stands for Case Sensitive and I'm sure you can work out CI
).
Jun 1, 2017 at 13:46
You can just use wildcards in the predicate (after IF, WHERE or ON):
@mainstring LIKE '%' + @substring + '%'
or in this specific case
' ' + @mainstring + ' ' LIKE '% ME[., ]%'
(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).
N
if your column is an nvarchar
, otherwise you get per-row conversions)
May 22, 2018 at 1:43
LIKE
operator supports RegEx, but LIKE
operator is not RegEx per se; this technique uses wildcard characters as literals when it searches for '% ME[., ]%'
, the [., ]
part is wildcard character group which checks for an optional period, comma, or space after the word "ME". Thanks!
Jun 17, 2021 at 17:42