String Functions – PATINDEX()


I am going to continue my series of very short articles or tidbits on Transaction SQL string functions. I will exploring the PATINDEX() function today.

The PATINDEX() function takes a search pattern to find and a expression to search as input parameters. It returns the first position in which the search pattern was found. Unlike the CHARINDEX() function, wild card characters such as %, _, and ^ can be used used to define the pattern. In a nutshell, it is a fuzzy match that is performed.

The following example is based upon the television jingle that I heard as a kid for Trix cereal.

The example below contains four test cases:

  1. Word is found in target string.
  2. Word is not found in target string.
  3. Starting position any word that starts with tr.
  4. NULL expression to find.
  5. NULL expression to search.

The results of four test cases are the following:

  1. 7 – Seventh character position is start of string.
  2. 0 – Expression to find not found.
  3. 14 – Expression is matched to trix.
  4. NULL – Position is unknown.
  5. ERROR – This function call generates an error.

Next time, I will be exploring the QUOTENAME() function that comes in handy when creating dynamic TSQL with object names that might need to be quoted.

Related posts

Leave a Comment