Otis wrote:
Ah, but isn't that similar to:
SELECT * FROM
(
SELECT ManagerID, COUNT(*)
FROM HumanResources.Employee AS e
WHERE ManagerID IS NOT NULL
GROUP BY ManagerID
) AS DirReps
ORDER BY ManagerID,
which is already possible in 2000 ? (though I've to read more about them I think to see the additional power of this, especially the recursive feature
Hi, my first post on the forum (thinking about buying LLBLGen...)
The key point about CTEs is the one Omar made about them being recursive, this is where they get their real power, as they increase the expressive power of the SQL language itself, it is not just a syntax change.
SQL as a language has some limits to its expressiveness, there are (to my knowledge) two classes of problem that cannot be directly represented in the language (in the same way as you would an INSERT). They are
a) graph problems, such as transitive closure or TSP
b) powerset (the set of all the possible combinations from a set of items)
These show up more often than you would expect in real business situations, the project I work on has great examples of both. For example, graph problems show up any time you have a hierarchy (of menus, BOM, categories or whatever) or travelling-salesman type optimisation, and powerset can show up in packing/optimisation problems.
The algorithm for solving these problems can be thought of as "start here...are we done..no..get more stuff...are we done...no...get more stuff..." and so on. SQL represents "get more stuff" with a JOIN, but if you don't know how many times you need to do it (just how many levels are there in your menu?) then you can't write it in a single SQL statement.
So these problems are usually solved by recursion (call to a stored proc) or iteration (with a CURSOR). CTEs will allow them to be solved directly in one statement.
http://msdn.microsoft.com/msdnmag/issues/04/02/TSQLinYukon/default.aspx
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsql90/html/sql_05TSQLEnhance.asp