Friday, 21 December 2018

Charindex function in SQL server

The Charindex function does not provide wildcard characters. The Charindex function is similar to the like operator and Patindex function. The Charindex function also returns an integer. The Charindex function operates on char, nchar, varchar, nvarchar, text, and ntext data types only. The charindex function returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found.

Syntax
CHARINDEX (exp1, exp2)
CHARINDEX (exp1, exp2, Start_position)

Expression1 - Exp1 is the string of characters to be found in exp2.
Expression2 - Exp2 is the position where the Charindex function will start looking for exp1 in exp2. The Charindex function returns an integer value.
Start_position – if we want to start the search from specific position then we need to provide that position.

See the example
select CHARINDEX('h','Bagesh kumar Singh')

           
It returns first match position from the string.
Suppose we want to search this character from a specific position then we need to use 2nd function with 3 parameters.
See the example:
select CHARINDEX('h','Bagesh kumar Singh',8)


         
Search start from 8th position.

Popular Posts