Common Table Expressions

  • so for example. I have the below. Is this the same basic principle as using an into #tablename and then querrying it? Are the CTE's specific to the runtime of a stored procedure or once their defined thay can be refferenced forever?

    WITH EmployeeSubordinatesReport (EmployeeID, LastName, FirstName, NumberOfSubordinates, ReportsTo) AS

    (

    SELECT

    EmployeeID,

    LastName,

    FirstName,

    (SELECT COUNT(1) FROM Employees e2

    WHERE e2.ReportsTo = e.EmployeeID) as NumberOfSubordinates,

    ReportsTo

    FROM Employees e

    )

    SELECT LastName, FirstName, NumberOfSubordinates

    FROM EmployeeSubordinatesReport

  • BaldingLoopMan (12/8/2009)


    so for example. I have the below. Is this the same basic principle as using an into #tablename and then querrying it? Are the CTE's specific to the runtime of a stored procedure or once their defined thay can be refferenced forever?

    WITH EmployeeSubordinatesReport (EmployeeID, LastName, FirstName, NumberOfSubordinates, ReportsTo) AS

    (

    SELECT

    EmployeeID,

    LastName,

    FirstName,

    (SELECT COUNT(1) FROM Employees e2

    WHERE e2.ReportsTo = e.EmployeeID) as NumberOfSubordinates,

    ReportsTo

    FROM Employees e

    )

    SELECT LastName, FirstName, NumberOfSubordinates

    FROM EmployeeSubordinatesReport

    They can only be referenced by the immediately following SELECT/INSERT/UPDATE/DELETE statement. Think of them more as a derived table.

  • If you haven't already, you may also want to read this article[/url].

  • Seriously? You can only use a CTE in the statement immediately following?

    When I read the article, the impression I got was that you could define a CTE at the top of something like a stored proc, then use it all the way through. Is my understanding wrong?

  • niall.baird (12/8/2009)


    Seriously? You can only use a CTE in the statement immediately following?

    When I read the article, the impression I got was that you could define a CTE at the top of something like a stored proc, then use it all the way through. Is my understanding wrong?

    Lynn Pettis(12/8/2009)


    They can only be referenced by the immediately following SELECT/INSERT/UPDATE/DELETE statement.

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • I *can* read Garadin. That is why I was questioning the above statement. Seems to me that defining a #table would be more use, as you can use it in more places - unless of course, I am missing something.

  • In SQL Server 2000, at a previous employer, I wrote several queries that used the same derived table several times in a single select statement. It was a royal pain to write, and when the derived table had to be modified it had to be modified in several places. Enter SQL Server 2005 and CTE's. Now, just before the select statement, I can define to "derived table" once and use it several times, just like a table in the select statement. If the CTE needs to be modified, one place to make the change.

    CTE's are very useful when used properly. Sometimes a temporary table is a better option in a stored proc.

  • That makes a bit more sense - thanks for explaining, Lynn

  • niall.baird (12/8/2009)


    I *can* read Garadin. That is why I was questioning the above statement. Seems to me that defining a #table would be more use, as you can use it in more places - unless of course, I am missing something.

    heh, I couldn't resist. 😉

    Seriously though, don't take Lynn's word for it, run up a quick test and see for yourself.

    They see a ton of usage even with their limitations. They *can* also incur less overhead than creating a temp table, depending on your usage.

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • All very useful info guys. Once again it appears the geniuses at sql server have designed a new way to do the same thing but w/ different syntax. Sure there are some minor performance gains as usual. Sorry for the disgruntled attitude. The gators lost, I just got in, and haven’t finished my coffee. Also I just ate about 2 lbs of bacon at an all u can eat breakfast buffet. Bacon is my weakness and I’m paying for it now.

    Personally i develop using the #tables then convert them to @tables where needed when moving my code to prod. I like the #tables in development because i can see what is in them after the process runs and so on. It's essential to the dev process.

    Perhaps i will start to integrate these CTE's going forward and be a good boy.

  • BaldingLoopMan (12/9/2009)


    All very useful info guys. Once again it appears the geniuses at sql server have designed a new way to do the same thing but w/ different syntax. Sure there are some minor performance gains as usual. Sorry for the disgruntled attitude. The gators lost, I just got in, and haven’t finished my coffee. Also I just ate about 2 lbs of bacon at an all u can eat breakfast buffet. Bacon is my weakness and I’m paying for it now.

    Personally i develop using the #tables then convert them to @tables where needed when moving my code to prod. I like the #tables in development because i can see what is in them after the process runs and so on. It's essential to the dev process.

    Perhaps i will start to integrate these CTE's going forward and be a good boy.

    Be careful using table variables. Since they do not have statistics, the Query Optimizer assumes that table variables always have 1 row regardless of actual number of rows. For a table variable with a few hundred rows, not bad, but when you get to thousands and more you won't get an optimal execution plan for the query.

  • Are u saying if i'm using a #table and it has 10,000 recs then the optimizer may not optimize properly? Interesting. Would it by using the CTE w/ 10,000 recs?

  • BaldingLoopMan (12/9/2009)


    Are u saying if i'm using a #table and it has 10,000 recs then the optimizer may not optimize properly? Interesting. Would it by using the CTE w/ 10,000 recs?

    No, #tables have statistics so the QO will know that the table has 10,000 records. An @table with 10,000 records, however, will be treated by the QO as if it had only 1 row. This may result in a less than optimal execution plan for the query.

  • BaldingLoopMan (12/9/2009)


    All very useful info guys. Once again it appears the geniuses at sql server have designed a new way to do the same thing but w/ different syntax. Sure there are some minor performance gains as usual. Sorry for the disgruntled attitude. The gators lost, I just got in, and haven’t finished my coffee. Also I just ate about 2 lbs of bacon at an all u can eat breakfast buffet. Bacon is my weakness and I’m paying for it now.

    Personally i develop using the #tables then convert them to @tables where needed when moving my code to prod. I like the #tables in development because i can see what is in them after the process runs and so on. It's essential to the dev process.

    Perhaps i will start to integrate these CTE's going forward and be a good boy.

    You can see what is in a CTE as well, just SELECT * from it. I'm actually intending to write an article on temp tables and how they're not evil... but they're not always applicable either. Derived tables / CTE's can provide a marked performance increase over temp tables / table variables *in some cases*. Every situation is different, and CTE's (or derived tables) definitely have their place.

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • not sure what ur saying about the selecting for a cte because u can sdo that w/ the #tables as well.

    However that is very interesting the the QO will look at a @table w/ n records and take it as having 1 record. That explains some search optimization i was doing years ago that wouldn't play nice.

Viewing 15 posts - 1 through 15 (of 15 total)

You must be logged in to reply to this topic. Login to reply