SQL Server PATINDEX function is a string function that returns the starting position of the first occurrence of a pattern in a specified expression.
Wildcard characters can be used with PATINDEX Functions. However, the % character must come before and follow pattern.
The Starting position of PATINDEX Function is 1.
Return type of PATINDEX :
bigint if expression is of the varchar(max) or nvarchar(max) data types otherwise int.
If pattern or expression is NULL then PATINDEX function returns NULL and if pattern or expression is zero then it returns zero.
PATINDEX ( '%pattern%' , expression )
Is a character expression that contains the sequence to be found.
Is an expression typically a column that is searched to find the specified pattern.
Lets loot at an example of PATINDEX Function in SQL Server.
Basic use of PATINDEX
The following Query checks a short character string for the starting location of the characters ‘SER’ and returns the location of character.
DECLARE @Str AS VARCHAR(30) = 'MICROSOFT SQL SERVER 2016' SELECT PATINDEX('%SER%', @Str) AS Result
Using wildcard characters with PATINDEX
The following Query uses % and _ wildcards to find the position at which the pattern ‘S’, followed by any one character and ‘L’ starts in the specified string.
DECLARE @Str AS VARCHAR(30) = 'MICROSOFT SQL SERVER 2016' SELECT PATINDEX('%S_L%', @Str) AS Result
When pattern or expression is not found
Patindex function returns 0 when pattern or expression is not found in string.
DECLARE @Str AS VARCHAR(30) = 'MICROSOFT SQL SERVER 2016' SELECT PATINDEX('%2019%', @Str) AS Result
1,908 total views, 3 views today