Hi,I'm trying to get the hang of recursive CTEs.In this test I am wanting to set a level for downstream replications, but am not getting the expected results.What am I doing wrong here?Resource : [url]http://msdn.microsoft.com/en-us/library/ms175972%28v=sql.105%29.aspx[/url][code="sql"]CREATE TABLE #RepData(PubSvr Varchar(50),PubDB Varchar(50),RepName Varchar(50),SubSvr Varchar(50),SubDB Varchar(50))INSERT INTO #RepDataVALUES ('Svr1', 'DB1', 'Rep_DB1', 'Svr2', 'DB1'), ('Svr1', 'DB2', 'Rep_DB2', 'Svr2', 'DB2'), ('Svr1', 'DB2', 'Rep_DB2', 'Svr3', 'DB2'), ('Svr2', 'DB1', 'Rep_DB1_a', 'Svr3', 'DB1'), ('Svr2', 'DB1', 'Rep_DB1_a', 'Svr4', 'DB1'), ('Svr3', 'DB2', 'Rep_DB2_b', 'Svr4', 'DB2')/* Expected resultsPubSvr PubDB RepName SubSvr SubDB LvlSvr1 DB1 Rep_DB1 Svr2 DB1 0Svr1 DB2 Rep_DB2 Svr2 DB2 0Svr1 DB2 Rep_DB2 Svr3 DB2 0Svr2 DB1 Rep_DB1_a Svr3 DB1 1Svr2 DB1 Rep_DB1_a Svr4 DB1 1Svr3 DB2 Rep_DB2_b Svr4 DB2 2*/WITH DBs (PubSvr, PubDB, RepName, SubSvr, SubDB, Lvl) AS( SELECT PubSvr, PubDB, RepName, SubSvr, SubDB, 0 AS Lvl FROM #RepData GROUP BY PubSvr, PubDB, RepName, SubSvr, SubDBUNION ALL SELECT R.PubSvr, R.PubDB, R.RepName, R.SubSvr, R.SubDB, Lvl+1 FROM #RepData R JOIN DBs D ON D.PubSvr = R.SubSvr AND D.PubDB = R.SubDB)SELECT PubSvr, PubDB, RepName, SubSvr, SubDB, LvlFROM DBsORDER BY Lvl, RepName OPTION (MAXRECURSION 2)/* Actual ResultsPubSvr PubDB RepName SubSvr SubDB LvlSvr1 DB1 Rep_DB1 Svr2 DB1 0Svr2 DB1 Rep_DB1_a Svr3 DB1 0Svr2 DB1 Rep_DB1_a Svr4 DB1 0Svr3 DB1 Rep_DB1_b Svr4 DB1 0Svr1 DB2 Rep_DB2 Svr2 DB2 0Svr1 DB2 Rep_DB2 Svr3 DB2 0Svr1 DB1 Rep_DB1 Svr2 DB1 1Svr1 DB1 Rep_DB1 Svr2 DB1 1Svr2 DB1 Rep_DB1_a Svr3 DB1 1Svr1 DB1 Rep_DB1 Svr2 DB1 2*/DROP TABLE #RepData[/code]Cheers
↧