-- Sample Data
Create Table TB (ID Int , Name Varchar ( 10 ), Parentid Int )
Insert TB Select 1 , ' Aaaa ' , 0
Union All Select 2 , ' Bbbb ' , 0
Union All Select 3 , ' CCCC ' , 0
Union All Select 4 , ' AAAA-1 ' , 1
Union All Select 5 , ' AAAA-2 ' , 1
Union All Select 6 , ' BBBB-1 ' , 2
Union All Select 7 , ' CCCC-1 ' , 3
Union All Select 8 , ' CCCC-2 ' , 3
Union All Select 9 , ' AAAA-1-1 ' , 4
Go
-- Create a processed Function
Create Function F_id ()
Returns @ Re Table (ID Int , Level Int , Sid Varchar ( 8000 ))
As
Begin
Declare @ L Int
Set @ L = 0
Insert @ Re Select ID, @ l, Right ( 10000 + ID, 4 )
From TB Where Parentid = 0
While @ Rowcount > 0
Begin
Set @ L = @ L + 1
Insert @ Re Select A. ID, @ L, B. Sid + ' , ' + Right ( 10000 + A. ID, 4 )
From Tb a, @ Re B
Where A. parentid = B. ID And B. Level = @ L - 1
End
Return
End
Go
-- Call a function for query
Select A. * , Name with indentation = Space (B. Level * 4 ) + A. Name
From Tb a, f_id () B
Where A. ID = B. ID
Order By B. Sid
Go
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.