CHARINDEX: Get index of the delimiting space

CHARINDEX: Get index of the delimiting space

.Net Framework has very useful String.IndexOf that returns position of first occurrence of given char or substring in string. Although there is no function named IndexOf in T-SQL you can achieve same result with CHARINDEX and PATHINDEX function.

CHARINDEX function as counterpart of IndexOf()

CHARINDEX function has the following syntax:

CHARINDEX(expression1, expression2 [, start_location])

expression1 - sequence of characters to be found
expression2 - column or expression that is searched
start_location - optional parameter, start position of searching

Example that search for first position of word "chart" in ProductDescription column could look like:

SELECT CHARINDEX('chart', ProductDescription) FROM Products

PATINDEX function

PATINDEX function works very similar to CHARINDEX. Unlike CHARINDEX, PATINDEX function has only two parameters and first parameter is pattern that can include wildcard parameters. Syntax is like this:

PATINDEX('%pattern%', expression)

pattern - string that optionally can contain wildcard characters (%)

expression - column or expression to be searched

Example that solves the same problem as above would be:

SELECT PATINDEX('chart', ProductDescription) FROM Products

CHARINDEX vs. PATINDEX

So, there are two solutions that simulate C# or VB.NET IndexOf() function. The logical question is, which is better and what is the difference between them?

CHARINDEX has three parameters and it is better choice if you need to specify search starting position.

PATINDEX supports patterns with wild characters _ or %, or match range with [ ] and [^ ] so you have much more options to define what you want to find.

How to simulate LastIndexOf() in T-SQL?

You can simulate LastIndexOf with CHARINDEX or PATINDEX combined with REVERSE function. REVERSE function, as the name suggests, returns reverse of character sequence. So LastIndexOf implementation example that finds last position of word "chart" in column ProductDescription would be:

SELECT CHARINDEX('chart', REVERSE(ProductDescription)) FROM Products

Using of CHARINDEX or PATINDEX as substitute for LIKE keyword

One more use of CHARINDEX and PATINDEX functions is to find whether or not given string exists in column or expression. Instead of LIKE keyword, you can use example like this that returns all rows that contain word "chart" in ProductDescription column:

SELECT * FROM Products WHERE CHARINDEX('chart', ProductDescription) > 0



Example -

DECLARE @FullName VarChar(25), @SpaceIndex TinyInt SET @FullName = 'www.java2s.com' -- Get index of the delimiting space: SET @SpaceIndex = CHARINDEX('java', @FullName)
-- Return all characters to the left of the space: SELECT LEFT(@FullName, @SpaceIndex - 1) GO

Output

-------------------------

www.
(rows affected)

Comments

Popular posts from this blog

Google to FTS Syntax Cheat Sheet

@@rowcount

Sql Index