– © 2011 –
Vishal (http://SqlAndMe.com)
DECLARE @string VARCHAR(128)
SET @string = 'PATINDEX
searches the string for the ' +
'first occurrence
of a specified '
+
'character/String/pattern'
SELECT
PATINDEX('%s_t%', @string) AS 's t',
PATINDEX('%pat%', @string) AS 'PATINDEX',
PATINDEX('%pat[^i]%', @string) AS 'pattern',
PATINDEX('%f[a-i]r%', @string) AS 'first' Result Set:
s
t PATINDEX
pattern first
———– ———– ———– ———–
17
1
87 38
First column uses the _ Wildcard, which matches any one character, which is between 's' and 't'.
The second column uses % Wildcard, which searches for 0 or more characters. It is same as using: CHARINDEX('pat', @string).
Third column uses a ^ Wildcard, which matches the characters not matching the specified set. Hence, ignoring the 'PATINDEX'.
Last column matches the characters specified in the range using [ ] Wildcard. Since the set specifies that only 'a' to 'i', it ignores the 'for'.
Pattern matching is based on the data collation. We can use COLLATE to enforce a case-sensitive search:
SELECT
PATINDEX('%[S]tring%', @string) AS 'string',
PATINDEX('%[S]tring%', @string COLLATE Latin1_General_CS_AI)
AS 'String'
Result Set:
string
String
———– ———–
23
80
Hope This Helps!
SQL SERVER – Search Text Field – CHARINDEX vs PATINDEX
April 8, 2007 by pinaldave
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:
Examples of PATINDEX:
Summary:
PATINDEX is CHARINDEX + WildCard Search. Use either of them depending your need.
USE AdventureWorks;GOSELECT CHARINDEX('ensure', DocumentSummary)FROM Production.DocumentWHERE DocumentID = 3;GOExamples of PATINDEX:
USE AdventureWorks;GOSELECT PATINDEX('%ensure%',DocumentSummary)FROM Production.DocumentWHERE DocumentID = 3;GOSummary:
PATINDEX is CHARINDEX + WildCard Search. Use either of them depending your need.
No comments:
Post a Comment