A tree structure table recursively obtains a node and all its child nodes.

Source: Internet
Author: User
-- Instance Database
Create Table [bt_area] ([ID] int identity (1, 1), [pid] int, name varchar (20 ))
Insert [bt_area] Select 0, 'China'
Union all select 0, 'America'
Union all select 0, 'Canada'
Union all select 1, 'beijing'
Union all select 1, 'shanghai'
Union all select 1, 'shandong'
Union all select 6, 'jining'
Union all select 7, 'micromountain'
Union all select 6, 'jinan'
Union all select 6, 'dezhou'
Union all select 2, 'newyork'
Union all select 2, 'san Francisco'
Go
-- Obtain database functions of itself and its descendants
Create Function [DBO]. [getselfandchildid] (@ pid int)
Returns @ Re table (id int)
As
Begin
Insert into @ Re select ID from bt_area where pid = @ PID
While @ rowcount> 0
Begin
Insert into @ Re select a. ID
From bt_area a inner join @ Re B on A. PID = B. ID
Where a. id not in (select ID from @ Re)
End
Insert into @ Re values (@ PID)
Return
End
-- Execute database functions
Select * From bt_area where ID in (select * From getselfandchildid (1 ))

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.