|
|
Question : Sorting a varchar field numerically
|
|
We have apartment numbers stored in the database as a small varchar. When I pull the apartments from a building and display them I'd like to show the apartments in numeric order as opposed to binary order that the order by returns in the query. Unfortunately CAST and CONVERT don't handle strings such as "10A" when trying to convert to an integer, they just give an error. I figured I could do a huge nested replace() call to pull out all characters except numbers but it seems like a huge waste and there must be an easier way. Is it easier to just pull the data and then sort it using ASP?
To summarize:
Right now I'm getting this: 1A 1B 10A 10B 2A 3C
What I'd like is: 1A 1B 2A 3C 10A 10B
Thanks in advance!
|
Answer : Sorting a varchar field numerically
|
|
heres a generic solution for you.
create or replace function get_number ( p_str_in in varchar2 ) return number deterministic is /* Variables */ -- Components of match. t_component sys.owa_text.vc_arr; -- Return string. v_ret number := 0; begin
if (sys.owa_pattern.match(p_str_in, '([0-9.]*).*', t_component)) then v_ret := t_component(1); end if;
return v_ret; end get_number; /
now to test it out: SQL> create table test ( 2 text varchar2(30) 3 ) 4 /
Table created.
SQL> insert into test values ('1A');
1 row created.
SQL> insert into test values ('22B');
1 row created.
SQL> insert into test values ('101Scribble');
1 row created.
SQL> insert into test values ('3temp');
1 row created.
SQL> insert into test values ('3.2test');
1 row created.
SQL> commit 2 /
Commit complete.
SQL> REM This next index is a function based index.. SQL> REM get your dba to grant you QUERY REWRITE SQL> REM or it will fail with ORA-01031: insufficient privileges SQL> create index test_idx1 on test (get_number(text)) 2 SQL> /
Index created.
SQL> select text 2 from test 3 order by get_number(text) 4 /
TEXT ------------------------------ 1A 3temp 3.2test 22B 101Scribble
SQL>
|
|
|
|