Thursday, December 1, 2011

String functions in Oracle

Dear reader, 
Writing few String functions available in Oracle:

--------------LENGTH------------------
SELECT EMPNAME, LENGTH(EMPNAME), LENGTH('MANAGER') FROM EMPLOYEE;
//Output
EMPNAME     LENGTH(EMPNAME)  LENGTH('MANAGER')
-------     --------------   -----------------
Saikumar        8            7
Deepak          6            7

--------------TRIM------------------
SELECT Length('deepak '), TRIM('deepak '),Length(TRIM('deepak ')) FROM tab;
7  deepak  6

SELECT TRIM(LEADING '#' FROM 'rajesh##') FROM dual;    //rajesh##
SELECT TRIM(LEADING '#' FROM '##rajesh##') FROM dual;  //rajesh##
SELECT TRIM('#' FROM '##rajesh##') FROM dual;          //rajesh
SELECT TRIM('#' FROM '##raj##esh##') FROM dual;        //raj##esh

--------------SUBSTR----------------
Source_Str, Start_Pos, End_Pos

Value of Start_Position     
Positive ==    Counts forward from the first character in source_string
Zero (0) ==    Counts forward from the first character in source_string (that is, 
            treats a start_position of 0 as equivalent to 1)
Negative ==    Counts backward from an origin that immediately follows the last character in source_string A 
            value of -1 returns the last character in source_string.

SELECT SUBSTR('ABCDEFG',0,6)  FROM dual; //ABCDEF
SELECT SUBSTR('ABCDEFG',0,7)  FROM dual; //ABCDEFG
SELECT SUBSTR('ABCDEFG',2,3)  FROM dual; //BCD
SELECT SUBSTR('ABCDEFG',6)  FROM dual;   //FG
SELECT SUBSTR('ABCDEFG',7)  FROM dual;   //G
SELECT SUBSTR('ABCDEFG',-2,7)  FROM dual; //FG
SELECT SUBSTR('ABCDEFG',-3,7)  FROM dual; //EFG

--------------INSTR------------------
INSTR is used to find the position of any particular character in a word which 
returns numeric value. It IS CASE sensitive.

SELECT instr('KUMAR','e') FROM dual;  //0, e IS NOT present
SELECT instr('KUMAR','m') FROM dual;  //0, NOT matched, CASE sensitive
SELECT instr('KUMAR','M') FROM dual;  //3, INDEX starts FROM 1 here.

--------------REPLACE----------------
Source_Str, OLD_VAL, NEW_VAL
SELECT REPLACE('Deepak kumar', 'De', 'Ra')  FROM dual; //Raepak kumar

--------------LPAD-------------------
Source_Str, Total_No_Char, Filling_Char
SELECT LPAD('Here we are', 11, '-_') FROM dual;  //Here we are
SELECT LPAD('Here we are', 16, '-_') FROM dual;  //-_-_-Here we are  
//SIMILAR is RPAD

No comments:

Post a Comment