Expression de table courante.

Une expression de table courante ( CTE pour common Table Expression ) ressemble beaucoup à une vue non persistante.

Syntaxe :

WITH nom_CTE ( nom_colonne,… )
AS
(
requete
)
SELECT * FROM nom_CTE

Exemple de code :

WITH selection AS (
SELECT identificateur_de_cellule,traffic,datepart(ww,date) as sem,ROW_NUMBER() OVER (PARTITION BY identificateur_de_cellule,datepart(ww,date) ORDER BY traffic) as OrderRank FROM TRAFFIC_CELLULES
)
SELECT * FROM selection where OrderRank < salespersonid='sp.SalesPersonID'
UNION ALL
selectionner
)
SELECT * FROM simpleRecursive

Exemple :

– Creation d’une table avec les données sous forme d’arbre
CREATE TABLE Employee_Tree( Employee_NM nvarchar(50), employee_ID int Primary Key, reportsTo int )
INSERT INTO Employee_Tree VALUES (‘Richard’,1,NULL)
INSERT INTO Employee_Tree VALUES(‘Stephen’,2,1)
INSERT INTO Employee_Tree VALUES(‘Clemens’,3,2)
INSERT INTO Employee_Tree VALUES(‘Malek’,4,2)
INSERT INTO Employee_Tree VALUES(‘Goksin’,5,4)

–Requete recursive
WITH SimpleRecursive(Employee_NM,Employee_ID,ReportsTo) AS
( SELECT Employee_NM, Employee_ID, ReportsTo FROM Employee_Tree WHERE Employee_ID = 2
UNION ALL
SELECT p.Employee_NM, p.Employee_ID, p.reportsTo FROM Employee_Tree p INNER JOIN SimpleRecursive A ON A.Employee_ID = P.ReportsTo
)
SELECT sr.Employee_NM AS Employee, et.Employee_NM As Boss FROM SimpleRecursive sr INNER JOIN Employee_Tree et ON sr.ReportsTo = et.Employee_ID

lien : http://sqlpro.developpez.com/cours/sqlserver/cte-recursives/

Laisser un commentaire