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 < 3
Exemple de code :
Use AdventureWorks
GO
WITH OrderCountCTE(SalesPersonID,OrderCount) AS (SELECT SalesPersonID,Count(*) FROM Sales.SalesOrderHeader WHERE SalesPersonID is Not Null GROUP BY SalesPersonID )
SELECT sp.SalesPersonID,oc.OrderCount,sp.SalesYTD
FROM Sales.SalesPerson sp INNER JOIN OrderCountCTE oc
ON oc.SalesPersonID=sp.SalesPersonID
ORDER BY oc.OrderCount
Requêtes récursives avec les CTE.
La véritable puissance des CTE émerge lorsque vous les utilisez récursivement pour effectuer des requêtes hiérarchiques sur des données structurées sous forme d'arbres.
Syntaxe :
With SimpleRecursive(field name) AS
(
UNION ALL
)
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
Partager