How To Find A Character In A String

How To Find A Character In A String


This is a straightforward command, once the syntax is known. The command is “CHARINDEX”:


The code CHARINDEX(‘ABCDE’,’C’,1) 

means “find the position of the character ‘D’ in the string ‘ABCDE’, starting at position 1.


The returned value is 4 in this case.


How To Find A Character In A String Starting From The Right


There is no explicit SQL command to do this. Instead, the string is reversed, and then the standard CHARINDEX command is used:


REVERSE(‘ABCDE’)

gives ‘EDCBA’


Now the standard CHARINDEX command is used:

CHARINDEX(REVERSE(‘ABCDE’),’D’,1)


This returns the value 2. This is how far the charcter ‘D’ is from the right of the string. 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s