Using Custum Table Expressions
i am writting a new procedure, and i wonder when is it a good idea to use custum table expressions
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Roei BarRank #1,271 · 1.4K reputationPosted Aug 8, 2009, 10:22 AM EDT
Kirtan PatelRank #292 · 8.6K reputationPosted Aug 8, 2009, 7:31 AM EDT
when Using scalar subqueries (such as the
(COUNT())cannot be grouped or filtered directly in the containing query.Similarly, when using SQL Server 2005's ranking functions -
ROW_NUMBER(),RANK(),DENSE_RANK(),and so on - the containing query cannot include a filter or grouping expression to return only a subset of the ranked results.
For both of these .
builck11 reputationPosted Aug 8, 2009, 7:38 AM EDT
i am talking about what microsoft calls CTE
here is a sample
;with BlaBla as
{
select * from bla
}
select * from BlaBla
when should i use this type of select
Kirtan PatelRank #292 · 8.6K reputationPosted Aug 8, 2009, 10:37 AM EDT
it is used to perform complex query like when you use count(*) and want to filter you need to write complex correlated queries to get the the result but using CTE you can get the same result by using Understandable Simple code
like consider the following query that uses count(*)
WITH Sales_CTE (SalesPersonID, NumberOfOrders, MaxDate) AS ( SELECT SalesPersonID, COUNT(*), MAX(OrderDate) FROM Sales.SalesOrderHeader GROUP BY SalesPersonID ) SELECT E.EmployeeID, OS.NumberOfOrders, OS.MaxDate, E.ManagerID, OM.NumberOfOrders, OM.MaxDate FROM HumanResources.Employee AS E JOIN Sales_CTE AS OS ON E.EmployeeID = OS.SalesPersonID LEFT OUTER JOIN Sales_CTE AS OM ON E.ManagerID = OM.SalesPersonID ORDER BY E.EmployeeID;When you construct simple Query to achieve the same query gets very complex and with using CTE it make it simple one
Hope this will be Help ful to understand the usage of CTE
Dont Forget to mark "Do you like Answer" will earn me some credit :)