Doing 90% of my work in ASP and VBA I often find that I forget about the CHARINDEX function within SQL Server!
In ASP I’d usually do something like:
p = instr(myString, " ")
to find the first instance of the space character within the string myString.
On SQL Server the equivalent is the CHARINDEX function.
This finds the first occurance of one string within another string.
For example:
CHARINDEX(" ","My Blog")
would return the value 3.
Microsoft’s full description of this function is as follows:
Syntax
CHARINDEX ( expression1 ,expression2 [ , start_location ] )
Arguments
expression1
Is an expression that contains the sequence of characters to be found. expression1 is an expression of the character string data type category.
expression2
Is an expression, typically a column searched for the specified sequence. expression2 is of the character string data type category.
start_location
Is the character position to start searching for expression1 in expression2. If start_location is not specified, is a negative number, or is zero, the search starts at the beginning of expression2. start_location can be of type bigint.
Return Types
bigint if expression2 is of the varchar(max), nvarchar(max) or varbinary(max) data types, otherwise int.
Remarks
If either expression1 or expression2 is of a Unicode data type (nvarchar or nchar) and the other is not, the other is converted to a Unicode data type. CHARINDEX cannot be used with text, ntext, and image data types.
If either expression1 or expression2 is NULL, CHARINDEX returns NULL when the database compatibility level is 70 or higher. If the database compatibility level is 65 or lower, CHARINDEX returns NULL only when both expression1 and expression2 are NULL.
If expression1 is not found within expression2, CHARINDEX returns 0.
CHARINDEX performs comparisons based on the collation of the input. To perform a comparison in a specified collation, you can use COLLATE to apply an explicit collation to the input.
The starting position returned is 1-based, not 0-based.