4

I'm quite new to PL/SQL and I need to get the names and count of the distinct characters in a string. E.g. if I have a string str="helloexample", I need to get output of distinct characters in str, i.e. heloxamp.

How can I do this?

8
  • I also tried WM_CONCAT but it is giving an invalid identifier error. Feb 7, 2013 at 10:24
  • please show some source code... what have you tried ? what exactly is not working ?
    – Yahia
    Feb 7, 2013 at 10:24
  • There isn't a built-in function for that. You need to write some PL/SQL code yourself.
    – Alen Oblak
    Feb 7, 2013 at 10:24
  • Show us your code what you have done till yet, so we'll be in a better position to help
    – asifsid88
    Feb 7, 2013 at 10:29
  • It has been already answered. Here it is
    – Rahul
    Feb 7, 2013 at 10:30

2 Answers 2

3

You can use regular expression as follows:

SET serveroutput ON
DECLARE
     str        VARCHAR2(20):='helloexample';
     str_length NUMBER;
     c          VARCHAR2(20):=NULL;
     d          NUMBER;
BEGIN
     str_length:=LENGTH(str);
     FOR i IN 1..str_length
     LOOP
          IF regexp_instr(c,SUBSTR(str,i,1))>0 THEN
               NULL;
          ELSE
               c:=c||SUBSTR(str,i,1);
          END IF;
     END LOOP;
     dbms_output.put_line(c);
END;

the answer would be:

heloxamp
1
  • But it is better use query that already answered someone. SELECT REPLACE (Wm_Concat (C), ',', '') FROM (SELECT SUBSTR ('helloexample', Rownum, 1) C, MIN (Rownum) Rn FROM Dual CONNECT BY Rownum <= LENGTH ( 'helloexample') GROUP BY SUBSTR ( 'helloexample', Rownum, 1) ORDER BY Rn ) X;
    – ajmalmhd04
    Jul 16, 2013 at 2:45
0

if WM_CONCAT isnt working for you, you can use this trick:

select rtrim(xmlagg(xmlelement(e, str)).extract('//text()'), ',') as output
  from (select substr(str, level, 1) str, level l,
               row_number() over (partition by substr(str, level, 1) 
                                      order by level) rn
          from (select 'helloexample' str  from dual) d
        connect by level <= length(str)
        order by level)
 where rn = 1;


SQL> select rtrim(xmlagg(xmlelement(e, str)).extract('//text()'), ',') as output
  2    from (select substr(str, rownum, 1) str, level l,
  3                 row_number() over (partition by substr(str, rownum, 1) order by level) rn
  4            from (select 'helloexample' str  from dual) d
  5          connect by level <= length(str)
  6          order by level)
  7   where rn = 1;

OUTPUT
--------------------------------------------------------------------------------
heloxamp

Not the answer you're looking for? Browse other questions tagged or ask your own question.