Home » SQL Server PATINDEX

SQL Server PATINDEX

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.

SYNTAX 

PATINDEX ( '%pattern%' , expression )

pattern
Is a character expression that contains the sequence to be found.

expression
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

 




Also Read..

CHARINDEX()

LEN()

DATALENGTH()

SUBSTRING()

REPLACE()

REPLICATE()

SQL Basics TutorialSQL Advance TutorialSSRSInterview Q & A
SQL Create tableSQL Server Stored ProcedureCreate a New SSRS Project List Of SQL Server basics to Advance Level Interview Q & A
SQL ALTER TABLESQL Server MergeCreate a Shared Data Source in SSRSSQL Server Question & Answer Quiz
SQL DropSQL Server PivotCreate a SSRS Tabular Report / Detail Report
..... More.... More....More
Power BI TutorialAzure TutorialPython TutorialSQL Server Tips & Tricks
Download and Install Power BI DesktopCreate an Azure storage accountLearn Python & ML Step by stepEnable Dark theme in SQL Server Management studio
Connect Power BI to SQL ServerUpload files to Azure storage containerSQL Server Template Explorer
Create Report ToolTip Pages in Power BICreate Azure SQL Database ServerDisplaying line numbers in Query Editor Window
....More....More....More




 545 total views,  1 views today

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.