SQL SERVER – Search Text Field – CHARINDEX vs PATINDEX

We can use either CHARINDEX or PATINDEX to search in TEXT field in SQL SERVER. The CHARINDEX and PATINDEX functions return the starting position of a pattern you specify.

Both functions take two arguments. With PATINDEX, you must include percent signs before and after the pattern, unless you are looking for the pattern as the first (omit the first %) or last (omit the last %) characters in a column. For CHARINDEX, the pattern cannot include wildcard characters. The second argument is a character expression, usually a column name, in which Adaptive Server searches for the specified pattern.

Example of CHARINDEX:

USE AdventureWorks;
GO
SELECT CHARINDEX('ensure', DocumentSummary)
FROM Production.Document
WHERE DocumentID = 3;
GO



Examples of PATINDEX:

USE AdventureWorks;
GO
SELECT PATINDEX('%ensure%',DocumentSummary)
FROM Production.Document
WHERE DocumentID = 3;
GO



Summary:
PATINDEX is CHARINDEX + WildCard Search. Use either of them depending your need.

Reference : Pinal Dave (https://darkslategrey-bat-805937.hostingersite.com) ,BOL – PATINDEX, BOL – CHARINDEX

SQL Function, SQL Scripts, SQL Server, SQL Server Security, SQL Utility
Previous Post
SQL SERVER – DBCC Commands Introduced in SQL Server 2005
Next Post
SQL SERVER – 2005 Reserved Keywords

Related Posts

Leave a Reply