sql >> Base de Datos >  >> RDS >> Sqlserver

Consulta recursiva en SQL Server

Prueba esto:

;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

Puede usar OPTION(MAXRECURSION n) para controlar la profundidad de recursión.

DEMOSTRACIÓN DE VIOLÍN DE SQL