Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Is this a good use of a CTE?

$
0
0
-- THE CODE OUTLINE OF A CTE(COMMON TABLE EXPRESSION)
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- WITH expression_name [ ( column_name [,...n] ) ]
-- AS
-- ( CTE_query_definition )
-- ***********************************

WITH WHO_IS_TOP_DOG (EMPLOYEEID, LASTNAME, FIRSTNAME, REPORTSTO, LEVEL) AS
(
	--ANCHOR
	SELECT EMPLOYEEID, LASTNAME, FIRSTNAME, REPORTSTO,  0 AS LEVEL
	FROM EMPLOYEES 
	WHERE REPORTSTO IS NULL
	
	UNION ALL
		
	--RECURSIVE
	SELECT E.EMPLOYEEID, E.LASTNAME, E.FIRSTNAME, E.REPORTSTO, LEVEL + 1
	FROM EMPLOYEES AS E
	INNER JOIN WHO_IS_TOP_DOG AS W
	ON E.REPORTSTO = W.EMPLOYEEID
)
SELECT * FROM WHO_IS_TOP_DOG


UML, then code


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>