Retrieve Parent Child Sub-Child recors in SQL Query

I've a self reference table and it has Parent-Child-Subchild relation. I'm getting an output (from second answer http://stackoverflow.com/questions/16031000/get-records-containing-all-the-child-records-in-sql-server) as expected, but it's
displaying results in below format.
<parent id> - <name> - <code>
<child id> - <name> - <code>
<child id> - <name> - <code>
<child id> - <name> - <code>
<child id> - <name> - <code>
<sub child id> - <name> - <code>
<sub child id> - <name> - <code>
<sub child id> - <name> - <code>
I want to display the results like in below format with applying some indent style to distinguish parent\ child\sub-child relationship.
<parent id> - <name> - <code>
<child id> - <name> - <code>
<child id> - <name> - <code>
<sub child id> - <name> - <code>
<sub child id> - <name> - <code>
<child id> - <name> - <code>
<child id> - <name> - <code>
<sub child id> - <label> - <code>
<child id> - <name> - <code>
<child id> - <name> - <code>
Please assist me on foumulating results as expected.

BOL has a good example of doing this in the CTE topic.  See http://technet.microsoft.com/en-us/library/ms175972%28v=sql.105%29.aspx Here is a slightly modified
version of what is in BOL.
CREATE TABLE #MyEmployees
EmployeeID smallint NOT NULL,
FirstName nvarchar(30) NOT NULL,
LastName nvarchar(40) NOT NULL,
Title nvarchar(50) NOT NULL,
DeptID smallint NOT NULL,
ManagerID int NULL,
CONSTRAINT PK_EmployeeID PRIMARY KEY CLUSTERED (EmployeeID ASC)
-- Populate the table with values.
INSERT INTO #MyEmployees VALUES
(1, N'Ken', N'Sánchez', N'Chief Executive Officer',16,NULL)
,(273, N'Brian', N'Welcker', N'Vice President of Sales',3,1)
,(274, N'Stephen', N'Jiang', N'North American Sales Manager',3,273)
,(275, N'Michael', N'Blythe', N'Sales Representative',3,274)
,(276, N'Linda', N'Mitchell', N'Sales Representative',3,274)
,(285, N'Syed', N'Abbas', N'Pacific Sales Manager',3,273)
,(286, N'Lynn', N'Tsoflias', N'Sales Representative',3,285)
,(16, N'David',N'Bradley', N'Marketing Manager', 4, 273)
,(23, N'Mary', N'Gibson', N'Marketing Specialist', 4, 16);
; WITH DirectReports(Name, Title, EmployeeID, EmployeeLevel, Sort)
AS (SELECT CONVERT(varchar(255), e.FirstName + ' ' + e.LastName),
e.Title,
e.EmployeeID,
1,
CONVERT(varchar(255), e.FirstName + ' ' + e.LastName)
FROM #MyEmployees AS e
WHERE e.ManagerID IS NULL
UNION ALL
SELECT CONVERT(varchar(255), REPLICATE (' ' , EmployeeLevel) +
e.FirstName + ' ' + e.LastName),
e.Title,
e.EmployeeID,
EmployeeLevel + 1,
CONVERT (varchar(255), RTRIM(Sort) + '| ' + FirstName + ' ' +
LastName)
FROM #MyEmployees AS e
JOIN DirectReports AS d ON e.ManagerID = d.EmployeeID
SELECT EmployeeID, Name, Title, EmployeeLevel
FROM DirectReports
ORDER BY Sort;
GO
drop table #MyEmployees;
Tom

Similar Messages

  • How to get cm:search to use the max attribute when creating the SQL query?

    When we use the max attribute in the cm:search tag, it does not seem to honor the max attribute when creating the SQL query. However, the result returned from the tag is limited to the number specified by the max attribute. Then the tag seems to work as intended, but the performance will be sub optimal when the SQL query returns unnecessary rows to the application.
    We use the cm:search tag to list the latest news (ordered by date), and with the current implementation we have to expect a decrease in performance over time as more news is published. But we can’t live with that. We need to do the constraint in the SQL query, not in the application.
    The sortBy attribute of cm:search is translated to “order by” in the SQL query, as expected.
    Is it possible to get cm:search to generate the SQL query with an addition of “where rownum <= maxRows”?

    Hi Erik,
    The behavior of a repository in regards to the search tag's max results parameter is dependent on the underlying repository's implementation. That said, the OOTB repository in WLP does augment the generated SQL to limit the number of rows returned from the database. This is done in the parsing logic. This behavior may differ with other repository implementations.
    -Ryan

  • How to get the parent window in sub-child controller class in javafx?

    how to get the parent window in sub-child controller class in javafx?

    You can get the window in which a node is contained with
    Window window = node.getScene().getWindow();Depending when this is invoked, you might want to check the Scene is not null before calling getWindow().
    If the window is a stage that is owned by another window, you can get the "parent" or "owner" window with
    Window owner = null ;
    if (window instanceof Stage) {
      Stage stage = (Stage) window ;
      owner = stage.getOwner();
    }

  • In a child opportunity, How to retrieve parent opportunity ID

    Hello,
    I know that in account object, there is a way to retrieve parent account id.
    Now, I would like to know if it is possible to retrieve the Parent Opportunity ID, while being in the chilf opportunity.
    I tried many syntax which all brings me a syntax error :
    JoinFieldValue('<Opportunity>',[<OpportunityId>],'<ParentoptyIntegrationId>')
    JoinFieldValue('<Opportunity>',[<OpportunityId>],'<ParentOpportunityId>')
    JoinFieldValue('<Opportunity>',[<OpportunityId>],'<ParentoptyExternalSystemId>')
    Thanks a lot for your help.
    Best regards,
    Julien

    Hi Julien,
    We cannot get the Row Id of the parent opportunity in the child object. However if you can convey what the requirement is, there could be another way of fulfilling the requirement.
    Regards,
    Paul

  • Hierarchical query to retrieve child.. sub-child .. so on

    Please help me writing a SQL Query to fetch all child tables and sub-children and so on for a given table in the following manner:
    TABLE_NAME LEVEL
    A 1
    AA 2
    AAA 3
    AB 2
    ABA 3
    ABB 3
    B 1
    BA 2
    BB 2
    I have written a query to give only the first level children.
    SELECT DISTINCT b.table_name, 1 level_no
    FROM user_constraints a, user_constraints b
    WHERE a.constraint_name = b.r_constraint_name
    AND a.table_name = :table_name;

    You can find multiple examples on http://asktom.oracle.com
    Ex.: http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:426166454665#9313682577033

  • Retrieving all FK from child table in a resultset

    I have a parent and its child table.In child table there are many records containing the same PK of the parent as a foreign key(one to many relationship).Now how can I get all those values (in a resultset) of child table containing the same FK .The code i produced can fetch the first record of the same PK of the parent.But how can I get all with a single SQl statement and iterate through them as necessary.
    String sql1="SELECT * FROM ChildTableName WHERE id= ' 100 ' ; //100 is the PK of Parent table // there are many records in Child Table having 100 as foreign key resultset = statement.executeQuery(sql1); resultset .next();      try{          System.out.println("Data> "+resultset.getString(1));         System.out.println("Data> "+resultset.getString(2));         System.out.println("Data> "+resultset.getString(3));   }catch(SQLException sqle){System.out.println("ERROR REFRESH : " + sqle); }{code} Edited by: Tanvir007 on Apr 17, 2008 4:35 AM Edited by: Tanvir007 on Apr 17, 2008 4:37 AM Edited by: Tanvir007 on Apr 17, 2008 4:40 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    duffymo wrote:
    First of all,ARE U BLIND brother, didn't you see what I wrote-
    String sql= "SELECT Flat_Rent.rent_id,Flat_Rent.flat_name FROM Month_Rent INNER JOIN Flat_Rent ON Month_Rent.rent_id = Flat_Rent.rent_id WHERE Flat_Rent.rent_id = '4-2008'" ;      
    Actually, I did see that. It makes me wonder why you were asking in the first place and what the problem is now.In the first place, I didnt use join,I did it later as u advised.But u asked me later about the join.Why?
    >
    People who have empty catch blocks are fools. If you don't want to be one, log or print the stack trace. It's good information to have, and it'll help you avoid problems in the future.People are fools for many reasons LIKE - even if I told u that I can retrieve record (but only the first record),there is no question of throwing an exception.And I DID fill catch block in the first place,look back.Later, it wasnt that much necessary bcos no exception throws at all.
    However brother many thanks for an attempt to help me.I think I have solved the problem-
    try{
    String sql= "SELECT flat_name,flat_rent,elec_bill FROM Month_Rent INNER JOIN Flat_Rent ON Month_Rent.rent_id = Flat_Rent.rent_id WHERE Flat_Rent.rent_id = '4-2008'" ;      
                             resultset = statement.executeQuery(sql);               
                             resultset .next();
                             do
                                  System.out.println("Flat Name>> " + resultset .getString(1));
                                  System.out.println("Rent>> " + resultset .getString(2));
                                  System.out.println("Elec Bill>> " + resultset .getString(3));
                             while(rs.next());
                        }catch(SQLException sqle){ sqle.printStackTrace();           }But the problem is, The fields in my DB are in this serial- rent_id,flat_name,flat_rent,elec_reading,elec_bill,total_rent,status
    But as you can see from the code that I get the Flat name in 1,Rent in 2 and bill in 3 which should be 2,3,5 respectively.Can you tell me why it is so?

  • Delete the parent records and child table records at a time

    hi all;
    I am facing the pbm like to delete the all records in child table and corresponding records in parent table at a time. so I want to delete the all the records in child table and corresponding parent records in parent table by using single SQL query. plz help me
    Thanks in advance

    You want to use one single SQL statement to delete the child records in a table and the corresponding master records in the master table??
    That's not quite possible with a single SQL, of course unless you are talking about Oracle Forms, where you have a relation and set the delete behavior to Cascading, like said in the above posts.
    Tony

  • How to obtain parent record from child record in relationship using API

    Hi,
    I have a record in the main table that is the child in a parent/child relationship to another main table record.  Using the Java API, how would I obtain the parent record in the relationship where I am starting with the child record?  In the API there seems to just be calls for getChildren, but not a getParent type call.
    Appreciate any immediate help that can be provided.
    Thanks,
    Eddie

    Hi Eddie,
    Please follow the below steps to retrieve only parents of a child Record.
    1. Create RetrieveRelationshipsCommand.
    2. Set the parameter RelationshipId.
    3. Set the parameter Anchor Record and Anchor Record Id. In this case the child record for which parents records to be retrieved.
    4. Set the parameter setGetChildren as false . This retrieves only the parent records for the specified child reocrd.
    5. Execute the RetrieveRelationshipsCommand.
    6. Retrieve member records from above step.
    Hope it helps
    Regards,
    Neeharika

  • Dynamic Rendering of Child Component based on SQL Query

    I want to preface this with I am very new to ADF.
    I have a page with a parent-multi child (tabbed) layout, and what I want to do is render one of the children based on the values of a sql query. I tried creating a manged bean but I had no idea how to get the database connection, so I added a method to my application module implementation instead. The method is of type boolean that runs my sql query and based on the results, returns true or false. I then set the tab's Rendered property to this method, #{bindings.method.execute}. Unfortunately, when I run the application the tab is not rendered, no matter what the value of the results. I therefore set a breakpoint on the code and ran it through the debugger, but the code is never being executed.
    If anyone could help, it would be greatly appreciated.
    I am running JDeveloper 11.1.1.3, hitting an Oracle 11g database, using ADF BC.
    Thanks,
    Michelle

    I don't really know what you mean, here is my code:
      public boolean checkLevel2Needed(String revwId)
        PreparedStatement stmnt = null;
        StringBuffer sql = new StringBuffer();
        Object[] procArgs = new Object[]{ revwId };
        ResultSet rs = null;
        boolean level2Required = false;
        System.out.println(revwId);
        sql.setLength(0);
        sql.append("Select count(*) as yesCount from usq.vu_review_response ");
        sql.append(" where revw_id = ? ");
        sql.append(" and gp_name = 'Level 1 Screen' ");
        sql.append(" and resp_text = 'Yes' ");
        try
          stmnt = getDBTransaction().createPreparedStatement(sql.toString(), 0);
          if (procArgs != null)
            for (int z = 0; z < procArgs.length; z++)
              stmnt.setObject(z + 1, procArgs[z]);
          rs = stmnt.executeQuery();
          if (rs.next())
            if (rs.getInt("yesCount")>0)
              System.out.println(rs.getInt("yesCount"));
              level2Required = true;
          rs.close();
        catch (SQLException e)
          throw new JboException(e);
        finally
          try
            if (stmnt != null)
              stmnt.close();
          catch (SQLException e) {}
        return level2Required;
      }But I don't think it is ever executing this code, the system.out.println's don't show up in the console and if I run it through the debugger with a breakpoint it never stops.
    What I really need is for this code to execute when I enter this page, and also any time the page is updated. Should I be using a backing bean?
    Thanks,
    Michelle
    Edited by: MSchaffer on Jan 6, 2011 5:27 PM

  • Sql query to retrieve records in parent sibling relationship in a table

    I need help to write this Sql query on a table where it has the primary_id, parent_id, and sibling_id. A new row can be created with or without the parent_id and sibling_id. However most of the new rows are created from an existing row and the primary_id
    of the existing row is inserted to the parent_id of the new row. This can go on for many many rows such as (B's parent_id has A primary_id, A's sibling_id has B primary_id), (C's parent_id has B primary_id, B's sibling_id has C primary_id), (D's
    parent_id has C primary_id, C's sibling_id has D primary_id), What I want is when user pass on a primary_id on a row, the query will give me back all the related parent_id or sibling_id records. For example User pass the A's primary_id the query will
    give me back the Row B and Row C as a sibling rows or user pass the C's primary_id the query should give me back row B and Row A as parent rows. Thanks
    Kahlua

    Check http://social.technet.microsoft.com/wiki/contents/articles/21062.t-sql-hierarchical-table-sorting-with-a-parent-child-relation.aspx
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • How can a parent restrict a child's access to a PARENT'S PRE-EXSISTING iTunes account via iCloud's Family Sharing Program?

    How can a parent restrict a child's access to a PARENT'S PRE-EXSISTING iTunes account via iCloud's Family Sharing Program?  To explain further... I have a young son who is on my iCloud family sharing program... I am excited to be able to share SOME of my music in my iTunes library, but there are some songs and music videos that are not age appropriate for him and currently there is no way to restrict him from viewing and downloading anything off of my iTunes library.  Yes, I suppose I can delete the songs he shouldn't have access to, but I don't think I should have to do that... I paid for them and still like them and listen to them while I work out or am without my kids.  Is there a way for me to personally select which songs/videos I would like to "hide" from my children in an effort to shield them from inappropriate content?

    Hello ggg39,
    Welcome to the Apple Support Communities!
    I understand that you have some content in your iTunes library that you would like to restrict access for the child set up on Family Sharing with you. To do this, you can set restrictions on the child’s device as described in the attached article. 
    Family Sharing - Apple Support
    Now kids under 13 can have their own Apple IDs. As a parent or legal guardian, the family organizer can create an Apple ID for a child and add the child to the family group automatically. Ask to Buy is turned on by default, and the organizer can also limit the content kids have access to on their devices through Restrictions on an iOS device or parental controls in OS X and iTunes.
    For more information on restrictions and how to set them up, please reference the next attached article. 
    About Restrictions (parental controls) on iPhone, iPad, and iPod touch - Apple Support
    Have a great day,
    Joe

  • Query Help with Parent, Child, Child's Child

    Hi all,
    Need some help with a query.  I'm trying to create a stored procedure that is sort of like a Customer, Order, Order, Details.  In my situation the tables are different but nevertheless, I want to grab all the fields from the  Parent, Child,
    and Childs' Child, where the Parent.ParentID = @Parameter.  I tried this:
    CREATE PROCEDURE [dbo].[spGetCompleteProjectXML]
    @ProjectID int = 0
    AS
    SELECT *,
    (SELECT *,
    (SELECT *
    FROM PageControls
    WHERE (PageControls.ProjectPageID = ProjectPages.ProjectPageID))
    FROM ProjectPages
    WHERE (ProjectPages.ProjectID = @ProjectID))
    FROM Projects
    WHERE (ProjectID = @ProjectID)
    FOR XML AUTO, ELEMENTS
    RETURN 0
    I think I'm close, but it was my best effort.  Could someone help?
    thanks in advance

    Hi TPolo,
    Regarding your description, are you looking for a sample like below?
    CREATE TABLE customer(customerID INT, name VARCHAR(99))
    INSERT INTO customer VALUES(1,'Eric')
    INSERT INTO customer VALUES(2,'Nelson')
    CREATE TABLE orders(orderID INT,customerID INT)
    INSERT INTO orders VALUES(1,1);
    INSERT INTO orders VALUES(2,1)
    INSERT INTO orders VALUES(3,2)
    INSERT INTO orders VALUES(4,2)
    CREATE TABLE orderDetails(orderID INT,item VARCHAR(99))
    INSERT INTO orderDetails VALUES(1,'APPLE1')
    INSERT INTO orderDetails VALUES(1,'BANANA1')
    INSERT INTO orderDetails VALUES(2,'APPLE2')
    INSERT INTO orderDetails VALUES(2,'BANANA2')
    INSERT INTO orderDetails VALUES(3,'APPLE3')
    INSERT INTO orderDetails VALUES(3,'BANANA3')
    INSERT INTO orderDetails VALUES(4,'APPLE4')
    INSERT INTO orderDetails VALUES(4,'BANANA5')
    SELECT customer.customerID,customer.name,
    (SELECT orderId,
    SELECT item FROM orderDetails WHERE orderID=orders.orderID FOR XML AUTO,TYPE,ELEMENTS
    FROM orders Where customerID=customer.customerID FOR XML AUTO,TYPE,ELEMENTS)
    FROM customer WHERE customerID=1
    FOR XML AUTO,ELEMENTS
    DROP TABLE customer,orderDetails,orders
    If you have any feedback on our support, please click
    here.
    Eric Zhang
    TechNet Community Support

  • Parent talking to child fails some of the time?

    Hi All,
    Have others found that sending a value (stored in a variable) from a parent (main timeline) to a child (movie clip) fails some of the time but only when the movie is running as a .swf (it never fails when testing in authoring)?
    My main timeline's actionscript has:
    XYZ_ChildMC.variableA = false; //parent talks to child movie clip
    In the child MC script:
    import fl.video.*;
    var variableA;
    function completeHandler(e: fl.video.VideoEvent): void
         if (variableA == false)
                 myFLV.seek(0);
                 myFLV..play();
    This seems to fail about 5% of the time when running/rerunning the .swf in a browser.
    Anyone have a similar experience?
    Thanks

    never had that problem.  most likely you have a timing issue.
    use the trace function or textfield to determine if completeHandler is executing before variableA is assigned.

  • Problem in relational blocks(Parent Child Grand Child

    Hi all
    I am working on Oracle Forms 10g Release-2.
    I am facing a problem in a form which consists three relational block. Blocks are organised as below:
    1.Parent >> 2.Child. >> 3.Grand Child.
    In 2.Child Block I have multiple records, each record has detail records in Grand Child block. Now if I move cursor from parent block to child block in a record(2nd,3rd or any other) other than first record for the first time, the child and grand child blocks flash out automatically.But if click on first record of child block for the fisrt time, then this problem is not happening.In Grand child block I am not facing this kind of problem.
    Thanks
    Mokarem.

    'Flash out' means Child block and grand child block is cleared autromatically, if I navidate to the child block for the first time. But if I navigate to first record of child block then I am not getting this problem, but if I click 2nd or higher then this problem is happening.
    Thanks
    Mokarem.

  • Automatic status heritage from parent item to child item in Instal Base R12

    Hi,
    Do you know please how to deactive automatic heritage of status from parent item to all child items of instal base when updating parent item status in R12?
    When I update status of package in Instal Base, statuses of all child items are updated automatically with same value.
    I am using R12 standard API's and I don't see any parameter that can help ...
    Must I see the Ebs parameters ? Profile options?
    Thx

    Did you check if the serial ABN656 is the parent and has child components under it? Check the below query for the same. Additionally you can also navigate to Oracle Installed Base Agent User responsibility, search for ABN656, click on the record, navigate to Configuration tab and see if this serial has any child components.
    select *
    from csi_ii_relationships cir
    ,csi_item_instances cii
    where cii.serial_number = 'ABN656'
    and cii.instance_id = cir.object_id
    Thanks
    Shree

Maybe you are looking for

  • "A How-To" on the steps to FIX the Problem of NO Sound Card DETECTION with AUDIGY 2 and Win XP

    Note#: When restarting the PC each time, shut off the main power switch on the Power Supply then back on. Note#2: You will need the Windows XP CD WITH the SP2 on it or have the download SP2 Install file from MS on your PC. I have it on CD. . Remove t

  • Duplicate calendar events with iCloud

    I would like to use icloud for my calendar on my iphone and mac desktop.  When I turn this calendar on though it duplicates all the events on my desktop and iphone too.  Any suggestions how to use it without having everything duplicate?

  • Delay execution time

    Hi Guys, I have two jsp page that load inside iFrames. One page sets a session variable that the other needs to read. The problem i am having is that the second jsp page sometimes renders before the the first one causing an error. I have tried the fo

  • Error 150:30 - License Recovery does not work

    Hi all, I downloaded the License Recovery for Mac to rectify the issue but it does not allow me to "Doubleclick the LicenseRecoveryLauncher.app and enter your Mac OS X password when prompted." it simply downloads the file to my desktop and I'm not su

  • Elegant solution for 'simple' problem?

    Hi, I'm writing a program which logs data to a text file. I want to change the file name each month. I need a subvi which will compare the month of the current iteration with the month of the last. I use get date/time in seconds, pass to seconds to d