Tuesday 21 December 2010

SQL Hints: How To Make SQL Do What You Want It To

Post a SQL "How To?" question in the  comments section here, and I will post the answer, if it is possible!

SQL provides very basic functionality, in terms of what can be searched for or filtered by. More advanced functions may be obtained, if the user knows a few tricks ... this blog exists to let users in on a few of the tricks that may be used, or algorithms that allow more information to be gleaned!


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 character 'D' is from the right of the string.

Coming soon, ...

How To Find The Number Of Occurrences Of One String Inside Another


How To Replace A Substring Inside A String

Take the Leftmost Part of a String Until a Certain Character is Reached


Calculate the Radius of a Point From Coordinates