SQL recursive query

Source: Internet
Author: User
Create Table [ Ptable ] (
[ ID ] [ Int ] Null ,
[ PID ] [ Int ] Null ,
[ Name ] [ Nchar ] ( 10 )
)
Go
Insert Into Ptable Values ( 1 , 0 , ' A ' )
Insert Into Ptable Values ( 2 , 0 , ' B ' )
Insert Into Ptable Values ( 3 , 1 , ' C ' )
Insert Into Ptable Values ( 4 , 1 , ' D ' )
Insert Into Ptable Values ( 5 , 2 , ' E ' )
Insert Into Ptable Values ( 6 , 3 , ' F ' )
Insert Into Ptable Values ( 7 , 3 , ' G ' )
Insert Into Ptable Values ( 8 , 4 , ' H ' )
Go

-- Query all the subnodes of Node 1.
With TMP As ( Select * From Ptable Where ID = 1
Union All Select Ptable. * From TMP, ptable Where TMP. ID = Ptable. PID
)
Select * From TMP

-- Query all the parent nodes of the eight nodes.
With TMP As (Select * From Ptable Where ID = 8
Union All Select Ptable. * From TMP, ptable Where TMP. PID = Ptable. ID
)
Select * From TMP;

-- Recursively Delete the statement of 1 node and all child nodes:
With TMP As ( Select * From PtableWhere ID = 1
Union All Select Ptable. * From TMP, ptable Where TMP. ID = Ptable. PID
)
Delete From Ptable Where Exists ( Select ID From TMP Where TMP. ID = Ptable. ID)

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.