Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Query ricorsiva in SQL Server

Prova questo:

;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

Puoi usare OPTION(MAXRECURSION n) per controllare la profondità di ricorsione.

DEMO SQL FIDDLE