How to make recursive query.Please help

Dear Experts:
I want to retrieve all employees located in a department in addition to all other employees located in the child's nodes of this department too.
Problem Details:
I have "Employees" table and "Departments" Table
The structure of Dept Table is:
ID   primary key
parent_dept   foreign key(id)
deptname  varchar2
deptType varchar2
The Employee table structure is
ID primary key
dept_id foreign key(Department.id)
empName varchar2Sample data for departments
ID : 1
parent_dept : null
deptname: General Manager office
deptType : 'GM'
ID :=2
parent_dept : 1
deptname: Information tech.
deptType : 'DPT'
ID :=3
parent_dept : 2
deptname: Software Development
deptType : 'SECTION'Sample Data for employees
ID : 101
dept_id  :1
empName  King
ID : 102
dept_id  :2
empName  ALAN
ID : 103
dept_id  :2
empName  SAM
ID : 104
dept_id  :3
empName  JANEI want to create a query that accepts a parameter "p_department_id" and returns All employees on the following conditions
1- In case the parameter value is null , then retrieve All Employees "king - alan- sam-jane"
2- In Case the parameter value is 1 , then retrieve all the employees under department id =1 in addition to all the employees located under the children departments.
in this case it will be "king - alan- sam-jane"
3- In case parameter value is 2 , then return all the employees under department id =2 in addition to all the employees located under the children departments.
In this case it will be " alan- sam-jane"
4- In case parameter value is 3 , then return all the employees under department id =3 in addition to all the employees located under the children departments.
in this case it will be only "JANE"
In brief , If I pass any value to the parameter :p_department_id , I want to retrieve all employees located in this department in addition to other employees located in the child's nodes of this department id
I use oracle database 11g release 2
Please help me
Thanks
Edited by: ta**** on Apr 3, 2013 5:56 PM
Edited by: ta**** on Apr 3, 2013 5:58 PM

SQL> variable p_department_id number
SQL> exec :p_department_id := null
PL/SQL procedure successfully completed.
SQL> with employees as (
  2                     select 101 id,1 dept_id,'King' empName from dual union all
  3                     select 102,2,'ALAN' from dual union all
  4                     select 103,2,'SAM' from dual union all
  5                     select 104,3,'JANE' from dual
  6                    ),
  7     departments as (
  8                     select 1 id,null parent_dept,'General Manager office' deptname,'GM' deptType from dual union all
  9                     select 2,1,'Information tech.','DPT' from dual union all
10                     select 3,2,'Software Development','SECTION' from dual
11                    )
12  select  *
13    from  employees
14    where dept_id in (
15                      select  id
16                        from  departments
17                        start with (
18                                       (
19                                            :p_department_id is null
20                                        and
21                                            parent_dept is null
22                                       )
23                                    or
24                                       id = :p_department_id
25                                   )
26                        connect by parent_dept = prior id
27                     )
28  /
        ID    DEPT_ID EMPN
       101          1 King
       102          2 ALAN
       103          2 SAM
       104          3 JANE
SQL> exec :p_department_id := 1
PL/SQL procedure successfully completed.
SQL> /
        ID    DEPT_ID EMPN
       101          1 King
       102          2 ALAN
       103          2 SAM
       104          3 JANE
SQL> exec :p_department_id := 2
PL/SQL procedure successfully completed.
SQL> /
        ID    DEPT_ID EMPN
       102          2 ALAN
       103          2 SAM
       104          3 JANE
SQL> exec :p_department_id := 3
PL/SQL procedure successfully completed.
SQL> /
        ID    DEPT_ID EMPN
       104          3 JANE
SQL> SY.

Similar Messages

  • Free cloud storage and unlimited access keeps popping up why and how to make it stop please help?

    free cloud storage and unlimited access keeps popping up why and how to make it stop please help?

    Safari
    Go step by by step and test.
      Quit Safari.
      Force Quit if you have to.
      Hold the shift key down and relaunch Safari.
    Reset Safari.
    Click Safari in the menu bar.
    From the drop down select "Reset Safari".
    Uncheck the boxes beside  all items.
    Just check the box beside “Remove all website data”.
    Click "Reset".
    Empty Caches
    Safari > Preference > Advanced
    Checkmark the box for "Show Develop menu in menu bar".
    Develop menu will appear in the Safari menu bar.
    Click Develop and select "Empty Caches" from the dropdown.
    Turn off Extensions if any, and launch Safari.
    Safari > Preferences > Extensions

  • How to make recursive query in oracle

    Dear Experts:
    I have "Employees" table and "Departments" Table
    The structure of Dept Table is:
    ID   primary key
    parent_dept   foreign key(id)
    deptname  varchar2
    deptType varchar2
    The Employee table structure is
    ID primary key
    dept_id foreign key(Department.id)
    empName varchar2Sample data for departments
    ID : 1
    parent_dept : null
    deptname: General Manager office
    deptType : 'GM'
    ID :=2
    parent_dept : 1
    deptname: Information tech.
    deptType : 'DPT'
    ID :=3
    parent_dept : 2
    deptname: Software Development
    deptType : 'SECTION'Sample Data for employees
    ID : 101
    dept_id  :1
    empName  King
    ID : 102
    dept_id  :2
    empName  ALAN
    ID : 103
    dept_id  :2
    empName  SAM
    ID : 104
    dept_id  :3
    empName  JANEI want to create a query that accepts a parameter "p_department_id" and returns All employees on the following conditions
    1- In case the parameter value is null , then retrieve All Employees "king - alan- sam-jane"
    2- In Case the parameter value is 1 , then retrieve all the employees under department id =1 in addition to all the employees located under the children departments.
    in this case it will be "king - alan- sam-jane"
    3- In case parameter value is 2 , then return all the employees under department id =2 in addition to all the employees located under the children departments.
    In this case it will be " alan- sam-jane"
    4- In case parameter value is 3 , then return all the employees under department id =3 in addition to all the employees located under the children departments.
    in this case it will be only "JANE"
    In brief , If I pass any value to the parameter :p_department_id , I want to retrieve all employees located in this department in addition to other employees located in the child's nodes of this department id
    Please help me
    Thanks

    This is the forum for SQL Developer, not for general SQL or PL/SQL questions.
    Please repost this in the SQL and PL/SQL forum.

  • Spry Accord. Panel - How to make it closed Please help!

    Hi, I would like to ask for your help with the following:
    I made a spry accord. panel. I was wondering how to make the first tab being closed when I open up the following page. Somehow when I made it, it created that the first tab stays open all the time. I was wondering if I can make it being closed and only open when I click on the Artisan Collection.
    Thank you so much for your help in advance! Agi
    Here is the link and you will see the panel on the left handside:
    http://mallinfurniture.com/browse_c01.html

    Hi,
    Thank you so much for the answers. I tried what you recommended. An error message came up saying the following. Also, I noticed something weird in my coding... Maybe that is why it is not working. I copy the coding as well. Thank you so much for taking the time to help me out!!!
    Error message: "This document contains JavaScript code for a widget that no longer exists. If you don't remove the code, the browser might display JavaScript errors when loading the page. Would you like Dreamweaver to find all the instances of this code for you?" Ok, No.
    When I click on Ok. Nothing happens. What am I doing wrong?
    Coding - the end of my page:
    <script type="text/javascript">
    <!--
    var Accordion1 = new Spry.Widget.Accordion("CatalogMenu", {defaultPanel: params.panel ? params.panel: 0});
    //-->
    </script>
    <script type="text/javascript">
    <!--
    var Accordion1 = new Spry.Widget.Accordion("Accordion1", { useFixedPanelHeights: false, defaultPanel: -1 }); //--> </script> </body>
    </html>
    It looks like I have double of that. When I removed the first accordion, all of my panels were opened...
    What could ne wrong?
    Thank you! Agi

  • NEED HELP!!!How to make LINES Colorful--PLEASE HELP!!!!!!

    i want to draw a red line:
    Graphics g;
    g = b.getGraphics();
    g.drawLine(20,5,100,64);
    but the line is black, i want it red.
    the command g.setColor(color.RED) is not working....
    WHATS WRONG, please help, thanks thomas

    Here is my code....
    mport com.ms.wfc.app.*;
    import com.ms.wfc.core.*;
    import com.ms.wfc.ui.*;
    import com.ms.wfc.html.*;
    import com.ms.awt.*;
    * Diese Klasse kann eine variable Anzahl von Parameter auf der Befehlszeile
    * entgegennehmen. Die Programmausf�hrung startet mit der Methode main(). Der
    * Klassenkonstruktor wird nicht aufgerufen, bevor nicht ein Objekt vom Typ 'exel'
    * in der Methode main() erstellt wird.
    public class exel extends Form
         String datum2="";
         String userdateinput="";
         int count=0;
         int i=0;
         int day7=0;
         int m=0;
         int p=0;
         public exel()
              super();
              for (i=0;i<31;i++)
              Point[count]="305";
         Graphics g;
         int xx1=5;
         int xy1=305;
         int xx2=600;
         int xy2=305;
         int yx1=5;
         int yy1=5;
         int yx2=5;
         int yy2=305;
         int i=0;
         //Bitmap b = new Bitmap("c:\\BACKGROUND.BMP");
         Bitmap b = new Bitmap(600,600);
         b.setTransparentColor(Color.RED);
         g = b.getGraphics();
         g.drawRect(0,0,600,600);
         g.drawRect(0,0,600,600);
         g.setBackColor(Color.RED);
    g.setColor(Color.RED);//HERE IS THE ERROR!!!
         g.drawLine(5,10,5,305);
         g.drawLine(5,10,10,10);
         g.drawLine(xx1,xy1,xx2,xy2);
         for (i=0;i<5;i++)
              yx1=5;
              yy1=60+yy1;
              yx2=10;
              yy2=yy1;
              g.drawLine(yx1,yy1,yx2,yy2);
         for (i=0;i<31;i++)
              xx1=xx1+15;
              xy1=305;
              xx2=xx1;
              xy2=300;
              g.drawLine(xx1,xy1,xx2,xy2);
         int h=0;
         int counter7=0;
         yx1=-10;
         int counter8=0;
         int counter6=0;
         for (h=1;h<31;h++)
              int cpoint=com.ms.wfc.util.Value.toInt(Point[h-1]);
              int cpoint2=com.ms.wfc.util.Value.toInt(Point[h]);
              yy1=305-(cpoint*3);
              yy2 = 305-(cpoint2*3);
              yx1=yx1+15;
              yx2 = yx1+15;
              if (cpoint==0)
                   yy1 = 0;
                   yy2 = 0;
                   yx1 = 0;
                   yx2 = 0;
              if (cpoint2==0)
                   yy1 = 0;
                   yy2 = 0;
                   yx1 = 0;
                   yx2 = 0;
              g.drawLine(yx1,yy1,yx2,yy2);
              if (cpoint==0)
                   for (counter6=0;counter6<counter7;counter6++)
                        yx1=yx1+15;
                        yx2 = yx1+15;
              if (cpoint2==0)
                   for (counter8=0;counter8<counter7;counter8++)
                        yx1=yx1+15;
                        yx2 = yx1+15;
              counter7++;
         pictureBox1.setImage(b);
              // Erforderlich f�r die Unterst�tzung des Visual J++-Formulardesigners
              initForm();          
              // ZU ERLEDIGEN: F�gen Sie beliebigen Konstruktorcode hinter den Aufruf von initForm hinzu
         * exel �berl�dt dispose, damit es die Komponentenliste
         * bereinigen kann.
    public void dispose()
         super.dispose();
         components.dispose();
    String DATUM="";
    private void start_click(Object source, Event e)
         /**DATE**/
         java.util.Date Date = new java.util.Date();
         java.sql.Date sqldate = new java.sql.Date(Date.getTime());
         String dat = String.valueOf(sqldate);
         //datum.setText(DATUM);
         //Start von EXEL
         try
              String makro="C:\\Program Files\\Microsoft Office\\Office\\XLSTART\\PERSONL.xls";
              String cmd = "C:\\Temp\\"+DATUM+"FLIP.xls";
              //String cmd = "C:\\Program Files\\Microsoft Office\\Office\\EXCEL.EXE Gr8galry.gra";
              String line = null;
              Process p1 = Runtime.getRuntime().exec(cmd);
              Process p2 = Runtime.getRuntime().exec(makro);
              //p.destroy();
         catch (java.io.IOException e1)
              //exception.setText("error");
    String Point[]=new String[31];
    private void button1_click(Object source, Event e)
         close();
    }

  • How to make a jar please help...this is urgent.

    hi guys, as you know i am a novice programer...I need to make a jar in order to reuse some of my servlet. but how I do that...please be kind to give me the instruction
    novice programer

    hi guys, as you know i am a novice programer...I need
    to make a jar in order to reuse some of my servlet.
    but how I do that...please be kind to give me the
    instruction
    novice programerTry these links:
    http://java.sun.com/j2se/1.3/docs/tooldocs/win32/jar.html
    http://java.sun.com/docs/books/tutorial/jar/

  • I forgot my icloud account and my email how can i recover it please help me icloud maker and icloud password and username holder

    i forgot my icloud account and my email how can i recover it please help me icloud maker and icloud password and username holder

    If you don't know your ID, you can try to find it as explained here: http://support.apple.com/kb/HT5625.  Then you can reset the password as explained here: http://support.apple.com/kb/PH2617.  Of course, you can only do this if it's your ID.

  • HT204230 this device is not longer eligible for creating a free i cloud accounting on my Iphone 5s , my old not working now cannot opened again just when i try make a free email this Message showed up  how i can fix it please help me  iPhone 5s, iOS 8.3

    this device is not longer eligible for creating a free i cloud accounting on my Iphone 5s , my old not working now cannot opened again just when i try make a free email this Message showed up  how i can fix it
    please help me
    iPhone 5s, iOS 8.3

    Create a new AppleID on a different iOS device or on a computer. You will
    then be able to use that newly created AppleID on your iPhone.

  • How to improve the performance of the attached query, Please help

    Hi,
    How to improve performance of the below query, Please help. also attached explain plan -
    SELECT Camp.Id,
    rCam.AccountKey,
    Camp.Id,
    CamBilling.Cpm,
    CamBilling.Cpc,
    CamBilling.FlatRate,
    Camp.CampaignKey,
    Camp.AccountKey,
    CamBilling.billoncontractedamount,
    (SUM(rCam.Impressions) * 0.001 + SUM(rCam.Clickthrus)) AS GR,
    rCam.AccountKey as AccountKey
    FROM Campaign Camp, rCamSit rCam, CamBilling, Site xSite
    WHERE Camp.AccountKey = rCam.AccountKey
    AND Camp.AvCampaignKey = rCam.AvCampaignKey
    AND Camp.AccountKey = CamBilling.AccountKey
    AND Camp.CampaignKey = CamBilling.CampaignKey
    AND rCam.AccountKey = xSite.AccountKey
    AND rCam.AvSiteKey = xSite.AvSiteKey
    AND rCam.RmWhen BETWEEN to_date('01-01-2009', 'DD-MM-YYYY') and
    to_date('01-01-2011', 'DD-MM-YYYY')
    GROUP By rCam.AccountKey,
    Camp.Id,
    CamBilling.Cpm,
    CamBilling.Cpc,
    CamBilling.FlatRate,
    Camp.CampaignKey,
    Camp.AccountKey,
    CamBilling.billoncontractedamount
    Explain Plan :-
    Description                    Object_owner          Object_name     Cost     Cardinality     Bytes     
    SELECT STATEMENT, GOAL = ALL_ROWS                              14     1     13
    SORT AGGREGATE                                                  1     13
    VIEW                         GEMINI_REPORTING               14     1     13
    HASH GROUP BY                                        14     1     103
    NESTED LOOPS                                        13     1     103
    HASH JOIN                                             12     1     85
    TABLE ACCESS BY INDEX ROWID     GEMINI_REPORTING     RCAMSIT          2     4     100
    NESTED LOOPS                                        9     5     325
    HASH JOIN                                        7     1     40
    SORT UNIQUE                                        2     1     18
    TABLE ACCESS BY INDEX ROWID     GEMINI_PRIMARY          SITE          2     1     18
    INDEX RANGE SCAN          GEMINI_PRIMARY          SITE_I0          1     1     
    TABLE ACCESS FULL          GEMINI_PRIMARY          SITE          3     27     594
    INDEX RANGE SCAN          GEMINI_REPORTING     RCAMSIT_I     1     1     5     
    TABLE ACCESS FULL     GEMINI_PRIMARY     CAMPAIGN                    3     127     2540
    TABLE ACCESS BY INDEX ROWID     GEMINI_PRIMARY          CAMBILLING     1     1     18
    INDEX UNIQUE SCAN     GEMINI_PRIMARY     CAMBILLING_U1                    0     1

    Hello,
    This has really nothing to do with the Oracle Forms product.
    Please, send the SQL or/and PL/SQL questions in the corresponding forums.
    Francois

  • I had my iphone5s in my shorts and my shorts went in the salt water at the beach and was wondering how to fix it or how much is it for another one. Im only 13 and we all make mistakes so please help 18 jan

    I had my iphone5s in my shorts and my shorts went in the salt water at the beach and was wondering how to fix it or how much is it for another one. Im only 13 and we all make mistakes so please help 18 jan

    Sorry, iPhones exposed to Salt Water, are pretty much destroyed. Salt Water is one of the most corrosive elements there is.
    Make an appointment at any Apple store & they will do an out of warranty exchange for US $269.

  • PROBLEM WITH HIERARCHICAL QUERY - PLEASE HELP

    I have got three tables :
    CREATE TABLE FIRM
    (FID INTEGER NOT NULL PRIMARY KEY,
    FNAME VARCHAR(40),
    FTYPE VARCHAR(3),
    MASTERID INTEGER );
    CREATE TABLE FACULTY
    (FAID INTEGER NOT NULL PRIMARY KEY,
    FANAME VARCHAR(40),
    FATYPE VARCHAR(3),
    MASTERID INTEGER );
    CREATE TABLE EMPLOYEE
         (EID INTEGER NOT NULL PRIMARY KEY,
    ENAME VARCHAR(20),
    ESURNAME VARCHAR(20),
         EJOB VARCHAR(3),
         MASTERID INTEGER );
    This is a hierarchical tree(or is ment to be, I,m complete rookie ) . Firm can be the root or can be slave to another firm. Faculty can be slave to firm, or to another faculty. Employee can be slave to faculty or to another employee(e.g. boss). This connections are specified by MASTERIDs.
    I need to write a procedure, which parameter would be node ID. It is meant to create a VIEW from this node as if it was a root (view of a subtree).
    I tried CONNECT BY clause but it works only on one table at a time and I have here three tables.
    I completely don,t know how to write it. Please help.

    create view hierarchy as
    select id, master_id, name from table1
    union all
    select id, master_id, name from table2
    union all
    select id, master_id, name from table3
    Then do your connect by query against hierarchy.
    It will not work in 8i (connect by on views not allowed), so you will need to materialize the view.
    Kirill

  • Sir, We have around 500 items as Insurance Spares in the stores. These spares are checked once in 6 months for their healthiness, storage, etc with a special checklist. We want this checklist an schedule in SAP ( MM). How to do it? Please help.

    Sir, We have around 500 items as Insurance Spares in the stores. These spares are checked once in 6 months for their healthiness, storage, etc with a special checklist. We want this checklist an schedule in SAP ( MM). How to do it? Please help.We are presently doing it as similar to PM schedule ( PM module) but want it in MM module.

    Hi Prerna
    Please refer the this doc ...it might help you
    http://www.erptips.com/Samples/ERPtips-SAP-Training-Manual-SAMPLE-CHAPTER-from-Basic-Quality-Management.pdf
    and kindly update the status if it works or not
    Regards
    Partha

  • I can't forcequit firefox and shutdown my computer, nor can I open up any other programs or applications. Does anyone know how to fix this? please help this poor soul.

    I can't forcequit firefox and shutdown my computer, nor can I open up any other programs or applications. Does anyone know how to fix this? please help this poor soul.

    You can force quit applications
    >Force quit
    if that does not work you can force quit a computer shut down by hold the power button for an extended period.

  • After upgrading my iPhone 5 to iOS 7 iTunes will not stay open once the app launches...does anyone know how to fix this? Please Help :)

    After upgrading my iPhone 5 to iOS 7 iTunes will not stay open once the app launches...does anyone know how to fix this? Please Help :)

    I have exactly the same problem. I too have tried everything that's been suggested, but still not working. Don't really what to do next? I have an iPhone 4S.

  • I recently moved and I got a new sim but I still use my old sim. I want to use both numbers for iMessage and FaceTime but i have absolutely no idea how to do it! please help me!

    I recently moved and I got a new sim but I still use my old sim. I want to use both numbers for iMessage and FaceTime but i have absolutely no idea how to do it! please help me! I have a macbook pro and iphone 5

    lewbobber wrote:
    Basically i need to either take it to a shop that can unlock i.e. £40.00
    Be aware, you go that route & every time you try to update or restore, it will error out, leaving your phone unusable. Not to mention, you void all warranty/support.
    Sell it & use the proceeds towards an officially unlocked iPhone bought directly from Apple.
    Good luck.

Maybe you are looking for

  • Duplicate Post - Please DELETE

    .

  • VE 108 or How can I update prices automatically

    Good day to everyone! I've got some problem with a tax determination in MM. Condition type - MWST. I created a personal condition table (501) with only field - Tax code. Also I changed access sequence for MWST with that table. I entered condition rec

  • Cursor as an IN Parameter

    Hello, I want to know if is possible to have (and the way to do it) a Cursor as an IN parameter. For example to have a cursor for insert some of its fields in a table. I have tried using a REF CURSOR in a package but it only works for returning a cur

  • Unicode and GUI_DOWNLOAD

    Hi! I'm on unicode system. If I try to use 'gui_download' function using 'BIN' file type, the system download a wrong file. If I open the file downloaded using notepad (for example) I see a blank space between one character and other. Can you help me

  • Non-Resident Alien Wagetypes

    Hello All, We are in the process of configuring for Non-Resident Alien processing in US Payroll.  I'm understanding that certain processing classes need to be using in order to process the correct taxes. My question is:  For every "income" type of wa