Solved

derived query

Posted on 2007-04-09
5
244 Views
Last Modified: 2008-02-01
Hi,
I have a table CH in SQL Server 2005 with columns ParentID (PK) and childID. ChildID could be the ParentID of Another ChildID. I want all the ChildID that are also the ParentIDs.

I have tried this:
Select ParentID From  (Select ChildID from ch) ch
   
But it does not work.
0
Comment
Question by:SA4
5 Comments
 
LVL 9

Accepted Solution

by:
gpompe earned 250 total points
ID: 18878502
Try this
select a1.ChildID from Ch a1 join Ch a2 on a1.ChildId=a2.ParentID
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 18878510
please try this:

WITH R ( ParentID, ChildID, Level )
AS (
   SELECT ParentID, ChildID, 0
   FROM CH
   WHERE ParentID IS NULl
UNION ALL
   SELECT c.ParentID, c.ChildID, R.Level + 1
   FROM R
   JOIN CH
     ON R.ChildID = CH.ParentID
   )
SELECT *
FROM R

http://www.eggheadcafe.com/articles/sql_server_recursion_with_clause.asp
0
 

Author Comment

by:SA4
ID: 18878786
thanks for the reply, I tried this:
WITH R ( ParentID, ChildID, Level )
AS (
   SELECT ParentID, ChildID, 0
   FROM CH
   WHERE ParentID IS NULl
UNION ALL
   SELECT c.ParentID, c.ChildID, R.Level + 1
   FROM R
   JOIN CH
     ON R.ChildID = CH.ParentID
   )
SELECT *
FROM R

But It does not give any result And I know that there are a few that I should be getting.
 
0
 
LVL 25

Assisted Solution

by:jrb1
jrb1 earned 250 total points
ID: 18879366
select parentid from ch where parentid in (select cihldid from ch)
0
 

Author Comment

by:SA4
ID: 18883354
thanks for your help.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Read about achieving the basic levels of HRIS security in the workplace.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now