Thursday, December 10, 2009

How to overcome Oracle Datatype VARCHAR2(4000) limitation

As we know there is limitations in oracle datatype VARCHAR2 as it can only hold data upto 4000 characters.

If you are trying to build some string which is going just beyond 4000 character limit and you are not willing to use BLOB or LONG, then you can split them and put
it into two different fields with datatype varchar2(4000)

For Example :

Employee Table (emp) :

EMPNO ENAME JOB MGR HIREDATE SALARY COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800
20
7499 ALLEN SALESMAN 7698 20-Feb-81 1600 300 30
7521 WARD SALESMAN 7698 22-Feb-81 1250 500 30
7566 JONES MANAGER 7839 2-Apr-81 2975
20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7839 1-May-81 2850
30
7782 CLARK MANAGER 7839 9-Jun-81 2450
10
7788 SCOTT ANALYST 7566 9-Dec-82 3000
20
7839 KING PRESIDENT
17-Nov-81 5000
10
7844 TURNER SALESMAN 7698 8-Sep-81 1500 0 30
7876 ADAMS CLERK 7788 12-Jan-83 1100
20

Now Lets understand the query below :

SELECT deptno, Substr(Sys_connect_by_path(path, '<>'), 3) hie
  FROM (SELECT deptno,
               ename,
               path,
               COUNT(1) over(PARTITION BY deptno) cnt,
               Row_number() over(PARTITION BY deptno ORDER BY ename) r_num
          FROM (SELECT deptno,
                       ename,
                       path,                       
              SUM((Length(path) + 2) - 2) over(PARTITION BY deptno, ORDER BY ename) len
                  FROM (SELECT deptno,
                               ename,
                               Substr(Sys_connect_by_path(ename, '\\'), 3) path
                          FROM emp
                         START WITH mgr IS NULL
                        CONNECT BY PRIOR empno = mgr))
         WHERE len < 20)
 WHERE r_num = cnt
 START WITH r_num = 1
CONNECT BY PRIOR r_num + 1 = r_num
       AND PRIOR deptno = deptno

No comments:

Post a Comment