Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Rekursive Abfrage in SQL Server

Versuchen Sie Folgendes:

;WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches M2
            ON M1.Product_Id = M2.matching_Product_Id
    WHERE M2.matching_Product_Id IS NULL
    UNION ALL
    SELECT
        C.Group_ID,
        M.matching_Product_Id
    FROM CTE C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID

Sie können OPTION(MAXRECURSION n) verwenden um die Rekursionstiefe zu steuern.

SQL-FIDDLE-DEMO