Often in our day to day sql query activities we require to retrieve the CHARINDEX from string value which we easily can achieve using tsql CHARINDEX . Requirements often extends to the scenario that we need to consider 1st occurance only or 2nd occurance only where we know the searched string may appear more than once in the value string. But in that case usage of CHARINDEX becomes bit complecated as we need to do lot of string manipulation to get the desired charindex position.
To overcome this limitation, I tried to extend the functionality of CHARINDEX with a new user defined function. This udf is actually based on 2 mostly used string functon CHARINDEX & SUBSTRING.
If we look at CHARINDEX signature it's CHARINDEX ( expression1 ,expression2 [ , start_location ] ). If we try to find 'A' from a string 'ABDABRCTAB' using CHARINDEX we need to call it as :
a) for the 1st occurance
CHARINDEX('AB','ABDABRCTAB',1)
b) for the 2nd occurance
CHARINDEX('AB','ABDABRCTAB',2) or CHARINDEX('AB','ABDABRCTAB',3) or CHARINDEX('AB','ABDABRCTAB',4)
c) for the 3rd occurance
CHARINDEX('AB','ABDABRCTAB', 5) or CHARINDEX('AB','ABDABRCTAB',6) etc
Actually we need to know before hand the where from we should start (ie start location)
But using my proposed udf (I've named it as ufnGetCharIndexWithOccurance) we need to call it as
ufnGetCharIndexWithOccurance ( expression1 ,expression2, intended_occurance)
where we need to search string <expression1> in string <expression2> for the occurance integer type of <intended_occurance>.
So if we reconsider the example explained above using this new udf the usage will be
a) for the 1st occurance
ufnGetCharIndexWithOccurance('AB', 'ABDABRCTAB', null) or ufnGetCharIndexWithOccurance('AB', 'ABDABRCTAB', 0) or ufnGetCharIndexWithOccurance('AB', 'ABDABRCTAB', 1)
b) for the 2nd occurance
CHARINDEX('AB','ABDABRCTAB',2)
c) for the 3rd occurance
CHARINDEX('AB','ABDABRCTAB', 3)
and so on.
Now this udf has been created keeping in mind, it will use the server Collation on which the function will be executed.
Sounds good !! So what's there to wait ... let's try using it and get rid off repeated usage of same code block !
Cheers !!