使用存储过程检查字符串是否包含 SQL Server 2005 中的子字符串 [英] Check if a string contains a substring in SQL Server 2005, using a stored procedure

查看:37
本文介绍了使用存储过程检查字符串是否包含 SQL Server 2005 中的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆