Google
Information Storage and Retrieval: Sort the String (SQL Puzzle 6)

Pages

Friday, July 4, 2008

Sort the String (SQL Puzzle 6)

Problem: You are given a string say 'dgfgkanb'. Give a SQL or PL/SQL logic to sort it.

PL/SQL Solution:
create a function as follows:
=============================================
create or replace function sort_string(original_string varchar2)
return varchar2 is
sorted_string varchar2(20):='';
cursor individual_string is
select ind from
(
select substr(original_string,rownum,1) ind from all_objects
where
rownum<=length(original_string) order by substr(original_string,rownum,1) );
begin
for rec2 in individual_string loop
sorted_string := sorted_string (concat) rec2.ind;
end loop;
return sorted_string;
commit;
end;
=============================
select sort_string('dgfgkanb') from dual
result : abdfggkn

I am not able to write a single SQL query to do this. Any help will be greatly appreciated....

1 comment:

Anonymous said...

Another Option for this
select * from
(select replace(sys_connect_by_path(t,' '),' ','') result from
(select t,rownum rn from
(select substr('&SortMe',rownum,1) t from all_objects
where rownum<=length('&SortMe')
order by 1))
connect by prior rn=rn-1
order by length(result) desc)
where rownum=1

Cheers
Kartik