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

Cara membuat kueri dari tabel hierarki anak induk

Jika Anda memiliki jumlah level yang tetap atau terbatas, Anda mungkin tidak memerlukan SQL DINAMIS. "Penguraian" jalur dapat diselesaikan dengan sedikit XML.

Pertimbangkan hal berikut:

Contoh:

Declare @YourTable Table ([Parent] varchar(50),[Child] varchar(50))
Insert Into @YourTable Values 
 (null ,'S-1')
,('S-1','S-11')
,('S-1','S-12')
,('S-1','S-13')
,('S-1','S-14')
,('S-1','S-15')
,('S-11','S-111')
,('S-11','S-112')

;with cteP as (
      Select Child
            ,Parent 
            ,PathID = cast(Child as varchar(500))
      From   @YourTable
      Where  Parent is Null
      Union  All
      Select Child  = r.Child
            ,Parent = r.Parent 
            ,PathID = cast(p.PathID+','+cast(r.Child as varchar(25)) as varchar(500))
      From   @YourTable r
      Join   cteP p on r.Parent  = p.Child)
Select [Group] = Child
      ,B.*
 From  cteP A
 Cross Apply (
                Select Level1 = xDim.value('/x[1]','varchar(max)')
                      ,Level2 = xDim.value('/x[2]','varchar(max)')
                      ,Level3 = xDim.value('/x[3]','varchar(max)')
                      ,Level4 = xDim.value('/x[4]','varchar(max)')
                      ,Level5 = xDim.value('/x[5]','varchar(max)')
                From  (Select Cast('<x>' + replace(PathID,',','</x><x>')+'</x>' as xml) as xDim) as X 
             ) B
  Order By PathID

Pengembalian




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Masukkan Karakter ke Tengah String di SQL Server (T-SQL)

  2. Memuat Gambar PictureBox Dari Database

  3. Bagaimana mengkonversi float ke varchar di SQL Server

  4. nvarchar(maks) vs NText

  5. Daftar string di SqlCommand melalui Parameter di C#