Hi, Can CTEs be called again and again with in SP Scope. See Code Follows: Create Proc TestCTEAS Begin With DataSet(EmployeeID,RowNumber) As (Select Employeeid,Row_Number() Over (Order by Employeeid asc) as RowNumber from employee where DateOfJoining < '12-Jan-2008') Select Top 1 * from DataSet; -- This Works FineSelect Top 5 * from DataSet; --- This Line gives Error "DataSet is Invalid Object"End
From BOL: "A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view." So, what you are trying to do, is invalid. However, you might use a view and use this in your procedure.
The only case you can use the cte more than once is when you use UNION, UNION ALL, JOIN,etc select columns from mycte where...... union all select columns from mycte where......
However, suppose that the same SELECT is issued in the procedure: The engine is smart enough to retrieve the data from a memory cache, right?
[quote user="EMoscosoCam"] However, suppose that the same SELECT is issued in the procedure: The engine is smart enough to retrieve the data from a memory cache, right? [/quote] Yes, the data is very likely to be retrieved from cache.
[quote user="jaybee"] Guys, what's a CTE? Also, was the 'With' statement (which is self-explanatory) introduced in SS2K5? [/quote] Refer this http://www.4guysfromrolla.com/webtech/071906-1.shtml