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

Kueri hierarkis di SQL Server 2005

Lihat ini

DECLARE @Table TABLE(
        ID INT,
        ReplacementID INT
)

INSERT INTO @Table (ID,ReplacementID) SELECT 1, NULL
INSERT INTO @Table (ID,ReplacementID) SELECT 2, 3
INSERT INTO @Table (ID,ReplacementID) SELECT 3, NULL
INSERT INTO @Table (ID,ReplacementID) SELECT 4, 5
INSERT INTO @Table (ID,ReplacementID) SELECT 5, 6
INSERT INTO @Table (ID,ReplacementID) SELECT 6, NULL

INSERT INTO @Table (ID,ReplacementID) SELECT 7, 8
INSERT INTO @Table (ID,ReplacementID) SELECT 8, 9
INSERT INTO @Table (ID,ReplacementID) SELECT 9, 10
INSERT INTO @Table (ID,ReplacementID) SELECT 10, NULL

SELECT * FROM @Table

;WITH repl AS (
    SELECT  *, 1 AS Depth
    FROM    @Table t
    UNION   ALL
    SELECT  r.ID,
            t.ReplacementID,
            r.Depth + 1
    FROM    repl r INNER JOIN
            @Table t ON r.ReplacementID = t.ID
    WHERE   t.ReplacementID IS NOT NULL
)
SELECT  repl.ID,
        repl.ReplacementID
FROM    (
            SELECT  ID,
                    MAX(Depth) Depth
            FROM    repl
            GROUP BY ID
        ) Depths INNER JOIN
        repl    ON  Depths.ID = repl.ID
                AND Depths.Depth = repl.Depth
ORDER BY 1



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Nilai bidang harus unik kecuali NULL

  2. SqlConnection melempar pengecualian saat berjalan tanpa debugging

  3. Concat dua kolom dalam pernyataan pilih sql server 2005

  4. Bagaimana Anda melakukan Versioning di Nhibernate?

  5. Kesalahan SQL Server 213:Nama kolom atau jumlah nilai yang diberikan tidak sesuai dengan definisi tabel.