Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 sql statement help

Author  Topic 

vinothrao84
Starting Member

21 Posts

Posted - 2009-07-26 : 21:53:27
hi,

i have the following table.

Parent ID.......ID.......Name
NULL..........10001.....Region1
NULL..........10002.....Region2
NULL..........10003.....Region3
10001.........501.......Test1
10001.........502.......Test2
10002.........503.......Test3
10002.........504.......Test4
10003.........505.......Test5
10003.........506.......Test6
501...........507.......Test7
501...........508.......Test8
502...........509.......Test9
502...........510.......Test10

Actually im doing a Treeview control in my ASP.NET application.
I can see the Parent Name, and its child popping out, BUT how to see the ID (501, 502) is having child in ParentID??

My SQL in ASP.NET is "SELECT ID, ParentID, Name FROM Test"
In order to show Child in the Parent, the ParentID has to be NULL.

Any idea??

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-07-28 : 02:34:19
is this u want

declare @str table( ParentID INT,ID int, Name varchar(32))
insert into @str select
NULL,10001,'Region1' union all select
NULL,10002,'Region2' union all select
NULL,10003,'Region3' union all select
10001,501,'Test1' union all select
10001,502,'Test2' union all select
10002,503,'Test3' union all select
10002,504,'Test4' union all select
10003,505,'Test5' union all select
10003,506,'Test6' union all select
501,507,'Test7' union all select
501,508,'Test8' union all select
502,509,'Test9' union all select
502,510,'Test10'

--select * from @str

;with cte(id,parentid,name,parentname)
as
(
select id,parentid,name,name from @str where parentid is null
union all
select t.id,t.parentid,t.name,c.name from @str t inner join cte c on c.id = t.parentid
)
select * from cte where parentid is not null order by 1
Go to Top of Page
   

- Advertisement -