Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Dapatkan semua orang tua untuk seorang anak

Coba ini untuk mendapatkan semua orang tua dari seorang anak

;with name_tree as 
(
   select id, parentid
   from Users
   where id = 47897 -- this is the starting point you want in your recursion
   union all
   select C.id, C.parentid
   from Users c
   join name_tree p on C.id = P.parentid  -- this is the recursion
   -- Since your parent id is not NULL the recursion will happen continously.
   -- For that we apply the condition C.id<>C.parentid 
    AND C.id<>C.parentid 
) 
-- Here you can insert directly to a temp table without CREATE TABLE synthax
select *
INTO #TEMP
from name_tree
OPTION (MAXRECURSION 0)

SELECT * FROM #TEMP

Klik di sini untuk melihat hasil

EDIT :

Jika Anda ingin menyisipkan ke dalam variabel tabel, Anda dapat melakukan sesuatu seperti:

-- Declare table varialbe
Declare @TABLEVAR table (id int ,parentid int)


;with name_tree as 
(
   select id, parentid
   from #Users
   where id = 47897 -- this is the starting point you want in your recursion
   union all
   select C.id, C.parentid
   from #Users c
   join name_tree p on C.id = P.parentid  -- this is the recursion
   -- Since your parent id is not NULL the recursion will happen continously.
   -- For that we apply the condition C.id<>C.parentid 
    AND C.id<>C.parentid 
) 
-- Here you can insert directly to table variable
INSERT INTO @TABLEVAR
select *
from name_tree
OPTION (MAXRECURSION 0)

SELECT * FROM @TABLEVAR

Klik di sini untuk melihat hasil



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara melihat log transaksi di SQL Server 2008

  2. SQL pilih maks (tanggal) dan nilai yang sesuai

  3. Cara Mengirim Email Hasil Query di SQL Server (T-SQL)

  4. Permintaan ODBC pada MS SQL Server mengembalikan 255 karakter pertama hanya dalam PHP PDO (FreeTDS)

  5. Membuat database secara terprogram di SQL Server