Check A String Contains Substring In SQL Server
In this article, I will explain how to check a string contains a substring or not in SQL Server.
There are two ways for check it. They are as given below.
1. CHARINDEX()
2. LIKE Predicate
3. PATINDEX function
3. PATINDEX function
Now start here one by one with practically.
1. CHARINDEX() :
This function is used to search a specific word or a substring
in whole string if it find out then returns it’s starting position. If it is
found, then it will return 0 (zero).
Let us understand this with examples.
Syntax
CHARINDEX ( SearchString,WholeString[ , startlocation ] )
Example:
- Declare @mainString nvarchar(100)='Amit Kumar Yadav'
- ---Check here @mainString contains Amit or not, if it contains then retrun greater than 0 then print Find otherwise Not Find
- if CHARINDEX('Amit',@mainString) > 0
- begin
- select 'Found' As Result
- end
- else
- select 'Not Found' As Result
Output :
Using CHARINDEX |
2. LIKE Predicate :
Any where in the given string.
Syntax :
LIKE '%' + Search Expression +'%'
- DECLARE @WholeString VARCHAR(50)
- DECLARE @ExpressionToFind VARCHAR(50)
- SET @WholeString = 'Amit Kumar Yadav'
- SET @ExpressionToFind = 'Kumar'
- IF @WholeString LIKE '%' + @ExpressionToFind + '%'
- PRINT 'Found'
- ELSE
- PRINT 'Not Found'
Output :
Like Predicate |
3. PATINDEX():
This function returns starting location of a pattern from given string.
Syntax:
PATINDEX('%Pattern%', yourString)
Example:
Output :
In above snapshot you can see PATINDEX() returns starting matching Index of substring from a string. It means expressionToFind is available in given string.
This function returns starting location of a pattern from given string.
Syntax:
PATINDEX('%Pattern%', yourString)
Example:
- DECLARE @WholeString VARCHAR(50)
- DECLARE @ExpressionToFind VARCHAR(50)
- SET @WholeString = 'dotnettechpoint'
- SET @ExpressionToFind = 'dot'
- SELECT PATINDEX ('%'+@ExpressionToFind+'%',@WholeString) AS RESULT
Output :
In above snapshot you can see PATINDEX() returns starting matching Index of substring from a string. It means expressionToFind is available in given string.
This function is used to search for specific word or substring in overall string and returns its starting position of match In case if no word found then it will return 0 (zero).
ReplyDeletehttps://www.mindstick.com/articles/12309/how-to-check-if-a-string-contains-a-substring-in-sql-server
This is my article on mindstick.
ReplyDelete