Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Recursive with path
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
IF OBJECT_ID('[dbo].[btree]', 'U') IS NOT NULL DROP TABLE [dbo].[btree]; GO CREATE TABLE [dbo].[btree] ( id INT PRIMARY KEY , parent_id INT REFERENCES [dbo].[btree] ([id]) , name NVARCHAR(20) ); GO INSERT INTO [btree] VALUES (1, null, '1 Root'); INSERT INTO [btree] VALUES (2, 1, '1.1 Group'); INSERT INTO [btree] VALUES (3, 1, '1.2 Group'); INSERT INTO [btree] VALUES (4, 2, '1.1.1 Group'); INSERT INTO [btree] VALUES (5, 2, '1.1.2 Group'); INSERT INTO [btree] VALUES (6, 3, '1.2.1 Group'); INSERT INTO [btree] VALUES (7, 3, '1.2.2 Group'); INSERT INTO [btree] VALUES (8, 4, '1.1.1.1 Items'); INSERT INTO [btree] VALUES (9, 4, '1.1.1.2 Items'); INSERT INTO [btree] VALUES (10, 5, '1.1.2.1 Items'); INSERT INTO [btree] VALUES (11, 5, '1.1.2.2 Items'); INSERT INTO [btree] VALUES (12, 6, '1.2.1.1 Items'); INSERT INTO [btree] VALUES (13, 6, '1.2.1.2 Items'); INSERT INTO [btree] VALUES (14, 7, '1.2.2.1 Items'); ;WITH tree AS ( SELECT c1.id, c1.parent_id, c1.name, [level] = 1, path = cast('root' as varchar(100)) FROM dbo.[btree] c1 WHERE c1.parent_id IS NULL UNION ALL SELECT c2.id, c2.parent_id, c2.name, [level] = tree.[level] + 1, Path=Cast(tree.path+'/'+cast(c2.id as varchar(10)) as varchar(100)) FROM dbo.[btree] c2 INNER JOIN tree ON tree.id = c2.parent_id ) SELECT tree.path, tree.id, parent_id, REPLICATE(' ', tree.level - 1) + tree.name AS description FROM tree Order by path OPTION (MAXRECURSION 0) ;
View schema
Execution time: 0,03 sec, rows selected: 14, rows affected: 14, absolute service time: 0,17 sec
edit mode
|
history
path
id
parent_id
description
1
root
1
NULL
1 Root
2
root/2
2
1
1.1 Group
3
root/2/4
4
2
1.1.1 Group
4
root/2/4/8
8
4
1.1.1.1 Items
5
root/2/4/9
9
4
1.1.1.2 Items
6
root/2/5
5
2
1.1.2 Group
7
root/2/5/10
10
5
1.1.2.1 Items
8
root/2/5/11
11
5
1.1.2.2 Items
9
root/3
3
1
1.2 Group
10
root/3/6
6
3
1.2.1 Group
11
root/3/6/12
12
6
1.2.1.1 Items
12
root/3/6/13
13
6
1.2.1.2 Items
13
root/3/7
7
3
1.2.2 Group
14
root/3/7/14
14
7
1.2.2.1 Items