Adsense Ad

Thursday, 11 May 2017

How to retrieve initial characters from string using SQL or PL/SQL



In SQL, use regexp_replace to complete the task.

Example:

SQL>  SELECT
  2   REGEXP_REPLACE(TRIM('HAA AAA SAA AAA NAA'),'(^| )([^ ])([^ ])*','\2') FIRST_LETTERS
  3   FROM DUAL;

FIRST_LETTERS
-------------
HASAN




In PL/SQL, use the following functions to complete the task.

Example1:

SQL> create or replace function get_initials(p_in varchar2) return varchar2 is
  2  RES VARCHAR2(100):= SUBSTR(P_IN,1,1);
  3  begin
  4  FOR I IN 1..LENGTH(P_IN) LOOP
  5    IF ASCII(SUBSTR(P_IN,I,1)) = 32 THEN
  6      RES:= RES || SUBSTR(P_IN,I+1,1);
  7      END IF;
  8    END LOOP;
  9    RETURN(RES);
 10  end;
 11  /

Function created

SQL> 
SQL> SELECT get_initials('HAAAA AAAAA SAAAAA AAAAA NAAAAA') FROM DUAL;

GET_INITIALS('HAAAAAAAAASAAAAA
--------------------------------------------------------------------------------
HASAN



Example2:

SQL> create or replace function get_initials(p_in varchar2) return varchar2 is
  2  RES VARCHAR2(100):= SUBSTR(P_IN,1,1);
  3  begin
  4  RES:= REGEXP_REPLACE(TRIM(p_in),'(^| )([^ ])([^ ])*','\2');
  5    RETURN(RES);
  6  end;
  7  /

Function created

SQL> SELECT get_initials('HAAAA AAAAA SAAAAA AAAAA NAAAAA') FROM DUAL;

GET_INITIALS('HAAAAAAAAASAAAAA
--------------------------------------------------------------------------------

HASAN


No comments: