Wednesday, 20 August 2008

Common Table Expressions

A Common Table Expression or CTE is best thought upon as a temporary view of data, it definition does not persist in the database or on the server, and its use is limited to once per query or batch, a second reference to it will throw an error as if the CTE no longer exists, in effect it doesn't exist anymore.

You start a CTE declaration using the WITH keyword, then specify how many fields it will expose, and then declare where it gets its data from (any valid SELECT statement).

-- this delcares a CTE called cteUsers
WITH cteUsers (UserID, EmailID)
AS (SELECT UserId, EmailID FROM tblUser WHERE UserID <>

-- this rerences the CTE
SELECT email FROM tblemail
INNER JOIN Users ON tblEmail.EmailId = Users.UserID


A second reference to the CTE in the same batch will throw an error

Server: Msg 208, Level 16, State 1, Line 7
Invalid object name 'users'.