T-SQL Tutorials - TSQLTutorials.com

WITH - Common Table Expressions


Introduction

The WITH Common Table Expression (CTE) is used for creating temporary named result sets. The functionality was introduced in SQL Server 2005. This T-SQL Expression begins with the keyword WITH. The results from the WITH expression are stored in a temporary named result set that can be queried. Using the WITH expression, allows for the simplification of query logic, by allowing the separation of logic into separate steps. The WITH expression has a few basic parts:

  • WITH [name of temporary resultset] (columns in result set)
  • AS ( SQL Query Definition )
following the 'WITH' keyword is the name of the temporary result set being created and the names of the columns in the result set. Parentheses are placed around the column names.

following the 'AS' keyword will be the SQL Query (surrounded by parentheses). The number of columns selected in the query must match the number of columns listed in the Table Expression Definition (the columns listed after name of resultset).




Beginning Example

This example will use the following table: SELECT Name, Position, Salary
FROM Employees
Here is the resultset from the above SELECT query:

NamePositionSalary
Joe GrapeManager80000
John PlumSoftware Developer65000
Frank AppleSoftware Developer62000
Patty PineappleSoftware Developer60000
Judy PeachSoftware Developer50000
Jane OrangeProject Manager75000

Using the WITH expression we can create a temporary named result set. In this example we will limit the result set to only the Software Developers from the above Employees table. WITH Developers (Name,Salary)
AS
(
SELECT Name, Salary FROM Employees WHERE Position = 'Software Developer'
)


SELECT * FROM Developers
Here is the resultset from the above SELECT query from the 'Developers' result set:

NameSalary
John Plum65000
Frank Apple62000
Patty Pineapple60000
Judy Peach50000


Microsoft SQL Server 2005 - Standard Edition 5 CAL's

Price: $1785
Buy It Now
SQL Server 2005 Enterprise Edition 1 CAL
Current Price: $4599.99
Current Bids: 0
228-00683 MS SQL Server 2000 Standard 5 CAL

Price: $375
Buy It Now
Microsoft SQL Server 2008 R2 Enterprise w/25 Device Cal
Price: $13049
Buy It Now
Microsoft SQL Server 2000 Standard 10 CAL 228-00684 NEW

Price: $939
Buy It Now
Microsoft SQL Server 2000 Standard Edition -Five CAL -

Price: $399
Buy It Now







Copyright 2010 - TSQLTutorials.com