Total Pageviews

Thursday, 1 May 2014

Understanding Ref Cursor with examples part 2



This is the continuation of the previous post ‘Ref Cursor Concept Part1’. In the previous post we have discussed type of ref cursors, Similarities of ref cursors with the static cursors, Rowtype_mismatch exceptions and assigning of one ref cursor variable into another ref cursor variable. In this edition we are going to discuss about how to pass ref cursor variable from one pl/sql unit to another,How we can use ref cursors in SQL statement and how to print data in sqlplus when the data is referenced by a ref cursor variable.
Passing Cursor Variables as arguments:-
As i told earlier that ref cursor variable can be passed from one programming unit to another as a argument of function and procedures. In the next example we are going to see that. But before that we must know that we are going to use EMP and DEPT table for the purpose.
SQL> SELECT  dname,loc FROM  dept WHERE deptno = 30;

DNAME          LOC
-------------- -------------
SALES          CHICAGO

SQL> SELECT  ename,deptno FROM emp WHERE empno='7499';

ENAME                    DEPTNO
---------- --------------------
ALLEN                        30

We will use this particular set of data for our example.

SET SERVEROUTPUT ON SIZE 20000;
DECLARE
  v_ref_emp  SYS_REFCURSOR;
  v_ref_dept SYS_REFCURSOR;
  v_ename    emp.ename%TYPE;
  v_deptno   emp.deptno%TYPE;
  v_dname    dept.dname%TYPE;
  v_loc      dept.loc%TYPE;
PROCEDURE Show_Emp_Loc_Dname(v_emp   IN     SYS_REFCURSOR,
                             v_dept  IN OUT SYS_REFCURSOR,
                             p_ename OUT    emp.ename%TYPE)
IS
BEGIN
  FETCH v_emp INTO p_ename,v_deptno;
  OPEN v_ref_dept FOR SELECT  dname,
                              loc
                        FROM  dept
                        WHERE deptno = v_deptno;
  v_emp.CLOSE;
END Show_Emp_Loc_Dname;
BEGIN
  OPEN v_ref_emp FOR SELECT  ename,
                             deptno
                       FROM  emp
                       WHERE empno='7499';
  --
  Show_emp_loc_dname(v_ref_emp,v_ref_dept,v_ename);
  --
    FETCH v_ref_dept INTO v_dname,v_loc;
    DBMS_OUTPUT.PUT_LINE(v_ename||' works in '||v_dname||' and his office is in '||v_loc);
    v_ref_dept.CLOSE;
END;
/
Output:-
anonymous block completed
ALLEN works in SALES and his office is in CHICAGO



In the above example we have taken two ref cursor variables(v_rfe_emp,v_ref_dept) to establish the fact.
1>     Firstly we have used v_ref_emp ref cursor variable to point the result set of the following query. (SELECT  ename, deptno FROM  emp WHERE empno='7499';).
2>     After that we have passed that ref cursor variable to a procedure Show_emp_loc_dname as an argument.
3>     Inside that procedure system fetch data which was pointed by v_emp_ref ref cursor (FETCH v_emp INTO p_ename,v_deptno;).So v_deptno holds the deptno ( here it is 30) in which
Employee number 7499 ( Here it is Allen) works.
4>     After that we have used v_ref_dept ref cursor variable to point out the department name and its location from dept table by using v_deptno variable.
5>     Now if you look into the signature of Show_Emp_Loc_Dname you will see that the v_ref_dept is declare as IN OUT variable. So after returning from Show_Emp_Loc_Dname in the body of main procedure system fetches the data referenced by v_emp_ref ref cursor (FETCH v_ref_dept INTO v_dname,v_loc).
6>     Basically we have sent one ref cursor into a procedure and from that procedure we have received another ref cursor.
7>     In next step we have print the name of the employee have empno=7499 and his respective department and location.
Using Ref Cursor In SQL Statements:-
CREATE OR REPLACE PACKAGE EXP_PIPE_ROW_EXAMPLE AS
  TYPE emp_data IS RECORD
  (
    ename  emp.ename%TYPE,
    empno  emp.empno%TYPE,
    job    emp.job%TYPE,
    deptno emp.deptno%TYPE
  );
  TYPE emp_data_set IS TABLE OF emp_data;
  FUNCTION Show_Emp_Record(p_deptno IN emp.deptno%TYPE) RETURN emp_data_set PIPELINED;
END EXP_PIPE_ROW_EXAMPLE;
--
CREATE OR REPLACE PACKAGE BODY EXP_PIPE_ROW_EXAMPLE AS
  FUNCTION Show_Emp_Record(p_deptno IN emp.deptno%TYPE) RETURN emp_data_set PIPELINED
  IS
  v_emp_ref        SYS_REFCURSOR;
  v_dyn_qry        VARCHAR2(2000) := NULL;
  v_count          NUMBER := 0;
  v_emp_rec emp_data;

  BEGIN
    v_dyn_qry := 'SELECT ename,empno,job,deptno from emp where deptno ='||p_deptno;
    OPEN v_emp_ref FOR v_dyn_qry;
    v_count := 0;
    LOOP
      FETCH v_emp_ref INTO v_emp_rec;
      EXIT WHEN v_emp_ref%NOTFOUND;
      PIPE ROW(v_emp_rec);
    END LOOP;
    CLOSE v_emp_ref;
    RETURN;
  END Show_Emp_Record;
END EXP_PIPE_ROW_EXAMPLE;

    SQL> select * from table(EXP_PIPE_ROW_EXAMPLE.Show_Emp_Record(10)); 
    ENAME           EMPNO JOB           DEPTNO 
    ---------- ---------- --------- ---------- 
    CLARK            7782 MANAGER           10 
    KING             7839 PRESIDENT         10 
    MILLER           7934 CLERK             10  

Print the Data in SQL plus which is pointed by ref cursor variable.
In the following way we can see a contents pointed by ref cursor variable.
SQL> CREATE OR REPLACE FUNCTION PRINT_REF_DATA RETURN SYS_REFCURSOR IS
  2    v_emp_ref SYS_REFCURSOR;
  3  BEGIN
  4    OPEN v_emp_ref FOR SELECT ename,empno,job,deptno from emp;
  5    RETURN v_emp_ref;
  6  END ;
  7  /

Function created.

SQL> VARIABLE v_emp REFCURSOR;
SQL> EXEC :v_emp := PRINT_REF_DATA;

PL/SQL procedure successfully completed.

SQL> PRINT v_emp_ref;
SP2-0552: Bind variable "V_EMP_REF" not declared.
SQL> PRINT v_emp;

ENAME                     EMPNO JOB                     DEPTNO
---------- -------------------- --------- --------------------
SMITH                      7400 CLERK                       20
SMITH                      7369 CLERK                       20
ALLEN                      7499 SALESMAN                    30
JONES                      7566 MANAGER                     20
MARTIN                     7654 SALESMAN                    30
BLAKE                      7698 MANAGER                     30
CLARK                      7782 MANAGER                     10
SCOTT                      7788 ANALYST                     20
KING                       7839 PRESIDENT                   10
TURNER                     7844 SALESMAN                    30
ADAMS                      7876 CLERK                       20

ENAME                     EMPNO JOB                     DEPTNO
---------- -------------------- --------- --------------------
JAMES                      7900 CLERK                       30
FORD                       7902 ANALYST                     20
MILLER                     7934 CLERK                       10

14 rows selected.


Thursday, 24 April 2014

MY FIRST ON SITE JOURNEY



                                                      MY FIRST ON SITE JOURNEY

It was just another lazy weekend for me when I heard the familiar voice of the postman of our locality, asking me to open the door. I saw quite surprised to see him because after the arrival of mobile phones in every hand their appearance has become quite rear.
“Hi” I simply addressed him with a voice mixed with some sort of surprise. He gave me a brown packet which had a label of government of India. It took no time to understand me that my passport has arrived for which I had applied for 6 months ago and almost forgotten.  Being a Bengali it is quite natural to have a wonder thirst inside me and studying computer engineering had multiplied the hunger to roam around all over the world which is officially known as “onsite”. To live with the dream one must have a passport which I got that day.
After that 2 years had passed and I was still waiting for the ‘D-Day’ to come in my life. It was November 2009 when I got one urgent call from my reporting manager Mr Subhroneel Ganguly. He told me that he wanted to see me in salt lake sector 5 office as soon as possible. After working hour I went to our head office to see him. I was little bit tensed at that moment because best of my knowledge the system I was looking after was working fine. Then why so he called me so urgently?
“May I come in sir” I knocked the door of our VP where my manager was also waiting for me.
“Come in, How are you” my manager replied with a smiling face which brought some sort of relief within me.
“So Anutosh , have you ever gone to eastern India before ?” My VP asked.
“No sir” I replied.
“So it’s your chance to explore eastern part of India “My manager said.
“I don’t understand” I said.
“Actually we are going to set up one payroll system for one of our client at Tizit, Nagaland. The payroll system  is  currently running in Kolkata office so all that we have to do is to install the software in respective server and you are going to entrain the company staffs so that they can use it efficiently.” My manger replied.
I was quite surprised and happy because it was going to be my first client visit experience or my first onsite travel. After two days our tickets were confirmed and we got it via email. On that very night I had seen majority of news channels were telecasting the increasing ALFA activity in   Assam. Just the day before boarding the plane I had received one call from our airline office that our direct flight from Kolkata to Dibrugarh was cancelled and we have to travel via Guwahati. It was good news at least for me because the direct flight was scheduled at 7 am in the morning which might cause difficulties for a person like me who stays nearly about 23 km away from airport. The new flight was scheduled at 10 am.
On the day of journey when I was about to leave my home suddenly I thought that it would be better to have a book with me because earlier I had experienced many boring hours on flight which I did not wanted to repeat. At that 11th hour I rushed to my room and picked up one book from my book self without even seeing the name of it.
It was 9 am and I was waiting for Subhroneel at the airport entrance gate. Sharply at 9:10 am he arrived and we went to took out boarding pass. After clearing security checking “tests” we were allowed to board the plane. It was the first time when Subhroneel was travelling by air so he had many question regarding the journey and I nothing to do but to answer. Even he got a window seat he preferred to sit in the middle. Sharply at 10 am the plane started moving and the speakers came alive with the voice of the pilot. After it’s took  off the air hostess started their routine work to inform us about the do and don’t in the plane and to negotiate problems in the time of any unexpected situation. Several minutes after floating in the air our plane shook for the first time due to some atmospheric reasons. We had got some more shakes within few minutes. Subhroneel was so afraid he asked me about the point told by the airhostess some time before. I assured him that everything was under control because if the situation was worst then definitely captain had addressed us already. But truly speaking I was in tension too because I had never faced so many shakings before in any flight.
The plane landed safely in Guwahati airport at 12 o clock .It was a shiny morning with freezing cold winds. The first thing anyone will observe in Guwahati airport is the military activity. Several men with automatic weapons in their hands were in position in the airport for security reasons. First time I saw some military helicopters in the airport like I had seen in many Hollywood action movies.
One of the flight attendants had informed us our next flight was scheduled at 1 pm. We got one hour time. First thing I did was to call to my parents in Kolkata. I was surprised to see that each time my call was disconnected by the service provider. The same thing happened with Subhroneel too. Latter we came to know that  due to security reasons government had ordered to block all outgoing calls which was originating  from pre paid mobiles of other states. “Oh my god ”, it was the exact expression which came to my mind at that time. I opened my bag and took out the book. It was OSAMA  written by Jonathan Randal. I started to read that book while Subhroneel was trying to contact his home.
After  30 minutes we were called for security checking. I must say security checking of Guwahati was more strict then Kolkata. I submitted both my hand bag and book to them. First thing they checked was my book. Still I can clearly remember the surprised expression of the security personnel to whom I had submitted the book. It was as if I had submitted any hazardous goods to them. He immediately called another two persons .For the next 5 mins they have checked each and every item of my bag and finally I was allowed to board the plane. It was more sophisticated than the previous one.
After one hour of journey we finally reached Dibrugarh airport. One person from client side was already present there to receive us. He informed us that last night ALFA had declared strike in Assam so we had to stay that day in Tinsukia district.  Still I can remember the natural beauty which I saw both sides of the roads. It was a wave of greenery . This place is famous for large tea gardens. When we reached our hotel it was almost 5 pm and sun was almost set. Even it was a strike but me and Subhroneel could not help our self without a short walking. It was 8pm in evening and every shop was closed and a very few people was there in the streets. First time in my life I had seen strikes making such a impact in people’s life.Luckly we found one PCO from where we had made calls to our homes.
Next day at 7:30am we started our journey to Tizit. Again it was a long exhausted journey but the natural beauty was so amazing I  could not even think to sleep in the car. Nearly after 4 hours we reached our destination.  Initially it looked like this.




It was the only factory of that area which imports logs from different parts of the country and makes ply from them. At 12 O clock we went to visit the office. The office was within the factory premises with some sort of modern facilities. Even in the village like Tizit I was surprised to see the modern computers with high speed broadband internet and satellite TV in the guest house. We started to work from the next day. Our on site manager was a very friendly person. The server setup and s/w installation, presentation took the first 2 days. Third day in the morning Subhroneel left for Kolkata. Now it was my trun to give training to some of the office stuffs.
Before coming to Nagaland some of my friends told me some horrible stories about the place but I think it was bad as it generally covered by the media. People of this part of the country are very simple and peaceful in nature. They are the most hard working people I had ever seen. I even saw some people even work for 15 hours a day. I was unable to talk with them because local language was not known to me.  Partho, who was living there for last 3 years helped me a lot to understand the people.  What he said was farming is the main occupation of 90% naga people. The population of Nagaland is very low compared to the other parts of the country .  Number of villages in this area is also very low so each village has got owner ship of huge land. I had also seen some people from other countries also staying there. They generally cultivate the unused lands of the villagers. In every village  there is a leader who controls the activities of local people. Partho told me that for last 3 years he had never observed anything like robbery, stealing, and communal mob which is quite common in bigger cities.
One thing which I had observed about tizit was the freedom of women. They truly work with male shoulder to shoulder with the same status. Some of them even works in the night shifts  and there was no report of any kind of abusing or harassments with them. When even in the bigger  cities like Mumbai, Bangalore, Kolkata security of woman workers is a big issue I think this part of the country can set an example in front of others. Majority of the people of tizit is christen. There is a nice church where they gather in every Sunday.
Every day after office hours me and Partho went to walking to see some different places. Some photos I had taken.
I can’t remember the name of the river but the water is very cool.


Market place of tizit.




Empty roads

Lapha mountain



Lapha bridge.


Little naga children.
It was really interesting to see some people prefers to stay in the mountains rather then the plain. Last place I had visited was lapha. He told me even some years ago Indian army regularly storms this places. collision between ALFA and the army was a common matter but now situation has changed. Ceasefire has been declared from both sides so now the area has become very peaceful to live.
In the meantime my training conducting session was over. It was a really good experience for me.My returning journey was not as happening as it was in the time of coming. My flight was scheduled at 9:30 am from Dibrugarh airport so I had to start my journey at 5:30 am in the morning. The driver of the car was very good in his skills. He took only 2:30 hours to reach the airport.
“Come again” he told me while waving his hands and I assured him if possible certainly I will return.
This time the flight was neither cancelled nor delayed .It took exactly 3 hours to reach Kolkata. Again the I got the busy streets, crowded bus, trains I was familiar with but still the little, unprivileged village had marked a permanent space in my memory “My first onsite journey”.