使用存储过程检查字符串是否包含 SQL Server 2005 中的子字符串 [英] Check if a string contains a substring in SQL Server 2005, using a stored procedure
问题描述
我有一个字符串,@mainString = 'Catch me if you CAN'
.我想检查ME
这个词是否在@mainString
里面.
I've a string, @mainString = 'CATCH ME IF YOU CAN'
. I want to check whether the word ME
is inside @mainString
.
如何在 SQL 中检查字符串是否具有特定的子字符串?
How do I check if a string has a specific substring in SQL?
推荐答案
CHARINDEX()
在更大的字符串中搜索子字符串,并返回匹配的位置,如果没有找到匹配,则返回 0
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 或来自 daniels 的回答,如果您想查找一个单词(而不是单词的子组件),您的 CHARINDEX
调用将如下所示:
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,',',' '),'.',' ') + ' ')
(为可能出现的任何其他标点符号添加更多递归 REPLACE() 调用)
(Add more recursive REPLACE() calls for any other punctuation that may occur)
这篇关于使用存储过程检查字符串是否包含 SQL Server 2005 中的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!