CHARINDEX (TSQL Function)
Returns the starting position (1-based) of a substring within a string.
Syntax
CHARINDEX ( substring , string_to_search [, start_location] )
Arguments
- substring
- is the substring to find within string_to_search. It is of type
varchar
. - string_to_search
- is the string to search. It is of type
varchar
. - start_location
- position at which the search starts (1-based). It is of type
int
.
If start_location is not specified or is <= 0, a value of 1 is used.
Return Types
Returns int
.
Remarks
If any argument is NULL, CHARINDEX
returns NULL.
If substring is not found, CHARINDEX
returns 0.
The collation used for string comparison depends on the collations of substring and string_to_search, similar to the case of the =
equality operator.
You can use the COLLATE
clause to force an explicit collation to a string argument.
The starting position returned is 1-based.
Examples
PRINT CHARINDEX('ivé', 'le printemps est arrivé très tôt cette année');
PRINT CHARINDEX('ivé', 'le printemps est arrivé très tôt cette année', 21);
PRINT CHARINDEX('ivé', 'le printemps est arrivé très tôt cette année', 22); -- not found
PRINT CHARINDEX('tôt', 'le printemps est arrivé très tôt cette année');
PRINT CHARINDEX('TOT', 'le printemps est arrivé très tôt cette année');
The result is:
21
21
0
30
30
Force a case sensitive and accent sensitive search by using COLLATE
clause on an input string:
PRINT CHARINDEX('tôt', 'le printemps est arrivé très tôt cette année' COLLATE french_cs_as);
PRINT CHARINDEX('TOT' COLLATE french_cs_as, 'le printemps est arrivé très tôt cette année'); -- not found
The result is:
30
0