Friday, January 9, 2009

Varchar Sequence Index Finder Oracle

Please refer how to generate varchar sequene in oracle? Prog. Findindgs.

As discussed in earlier post, that varchar sequence generator helps to generate character or string sequence very similar to number sequence in oracle.
Varchar sequence: A, B, C … Z, AA, AB, AC….AZ, BA, BC …BZ…ZA, ZB… ZZ, AAA, AAB…ZZZ, AAAA…..
This post is to do vise versa.
That is to get the sequence index value when user gives the varchar value.










InputOutput
A1
Z26
AZ 52
GCPB125478
ZA677
ZZZ18278
AAAA18279


Oracle function:-
CREATE OR REPLACE FUNCTION GetIndexOfStr(argVal VARCHAR)
RETURN NUMBER
IS
tmpIndex NUMBER;
tmpLength NUMBER;
BEGIN
--Getting the length of given varchar value
tmpLength:=LENGTH(argVal);
tmpIndex:=0;
--Calculating the index of the given varchar value in sequence
--A, B, C … Z, AA, AB, AC….AZ, BA, BC …BZ…ZA, ZB… ZZ, AAA, AAB…ZZZ, AAAA…..
FOR i IN 1 .. tmpLength
LOOP
tmpIndex:=tmpIndex+(ASCII(SUBSTR(argVal,i,1))-64)*POWER(26,tmpLength-i);
END LOOP;
--returning the given varchar index in the sequence
RETURN tmpIndex;
END;
Output:-
Run below query
SELECT GetIndexOfStr('ZZZ') as Sequence_Index FROM dual
Which will return the Index of ‘ZZZ’ in the considered varchar sequence
A, B, C … Z, AA, AB, AC….AZ, BA, BC …BZ…ZA, ZB… ZZ, AAA, AAB…ZZZ, AAAA…..
Result is 18278, since Index of 'ZZZ' in the considered varchar sequence is
18278



1 comment:

Unknown said...

This was so helpful to me--thank you so much. We have a revision code that is a,b,c....z,aa,ab,ac...and I needed to have it sorted in order. I added: (ASCII(SUBSTRING(revision_no,1,1))-64)*POWER(26,0)+ (ASCII(SUBSTRING(revision_no,2,1))-64)*POWER(26,1)as revnumber,
and ordered by revnumber DESC. It worked like a charm.