Microsoft SQL Server database help,articles and t-sql Tips, Business Intelligence, Interview questions and tutorials etc..
Wednesday, June 13, 2012
Query to get the parent level and child level hierarchy data of a particular account.
Declare @TestTable Table
(
ID int,
Name varchar(50),
ParentID int
)
Insert into @TestTable values
(1,'A',null),
(2,'Aa',1),
(3,'Aaa',1),
(4,'Ab',2),
(5,'Abb',4),
(6,'B',null),
(7,'Ba',6),
(8,'Bbb',7),
(9,'Abc',4),
(10,'Acc',9)
Declare @ID int = 4
;with cte
(
ID,Name,ParentID
)
As
(
Select ID,Name,ParentID
From @TestTable where ID = @ID
Union All
Select a.ID , a.Name,a.ParentID
from cte c inner join @TestTable a on c.ParentID = a.ID
)
,
cte1
(
ID,Name,ParentID
)
As
(
Select ID,Name,ParentID
From cte where ParentID is null
Union All
Select a.ID , a.Name,a.ParentID
from cte1 c inner join @TestTable a on a.ParentID = c.ID
)
Select * from Cte1 Option (MAXRECURSION 32767)
Labels:
T-Sql
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment