SQL Server 2000/2005 recursion

Source: Internet
Author: User

/*

Recursive query for Paint poly
---implementation in a SQL Server 2005 environment:

*/
--Generate test data
CREATE TABLE Dept (ID int,parentid int,msg varchar (20))
Insert INTO Dept select 1,0, ' d '
Insert INTO Dept Select 2,1, ' s '
Insert INTO Dept select 3,1, ' NL '
Insert INTO Dept select 4,2, ' d '
Insert INTO Dept Select 5,3, ' s '
Insert INTO Dept select 6,5, ' F '
Insert INTO Dept select 7,6, ' d '
Go

SELECT * FROM Dept
Declare @Id Int
Set @Id = 1; ---Modify the parent node here

With Rootnodecte (id,parentid,msg)
As
(
Select id,parentid,msg from Dept
Where ParentID in (@Id)
Union All
Select dept.id,dept.parentid,dept.msg from Rootnodecte
Inner Join Dept
On rootnodecte.id = Dept.parentid
)
Select * from Rootnodecte

---implementation in a SQL Server 2000 environment:
--Generate test data Geovin Du
CREATE TABLE Dept (ID int,parentid int,msg varchar (20))
Insert INTO Dept select 1,0, ' d '
Insert INTO Dept Select 2,1, ' s '
Insert INTO Dept select 3,1, ' NL '
Insert INTO Dept select 4,2, ' d '
Insert INTO Dept Select 5,3, ' s '
Insert INTO Dept select 6,5, ' F '
Insert INTO Dept select 7,6, ' d '
Go

SELECT * FROM Dept


--Create a user-defined function
Create function [dbo]. [Getchild] (@ID varchar (10))
Returns @t table (ID varchar), ParentID varchar (ten), msg varchar (+), level int)
As
Begin
DECLARE @i int
Set @i = 1
Insert INTO @t Select @ID, @ID, null,0-current level, this level, if not, you can comment out or add a parameter to select the operation
Insert INTO @t select Id,parentid,msg,@i from Dept where parentid = @ID

While @ @rowcount <>0
Begin
Set @i = @i + 1
INSERT INTO @t
Select
A.id,a.parentid,a.msg,@i
From
Dept A,@t b
where
A.parentid=b.id and b.level = @i-1
End
Return
End


--Execute Query
Select ID from dbo. Getchild (2)
Go

--Delete test data
Drop function Getchild
drop table Dept

SQL Server 2000/2005 recursion

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.