Using common table expressions in SQL Server 2005 queries
Takeaway: Common table expressions (CTEs), a powerful and slick new feature in SQL Server 2005, make your SQL more readable and easier to maintain. Arthur Fuller demonstrates how you can use a CTE more than once in a SQL Server statement.
New in SQL Server 2005 are common table expressions (CTEs). They are similar to aliases (as in SELECT T1.* FROM MyTable T1) but much more useful. In essence, a CTE is a temporary result set that exists only within the scope of the statement in which it occurs. You can create a CTE within a SELECT, INSERT, DELETE, UPDATE, or CREATE VIEW statement. CTEs resemble derived tables but with several advantages.
Advantages of CTEs
Unlike derived tables, CTEs can reference themselves. You can use a CTE in place of a view when you don't need to store the view. You can also reference the CTE multiple times within a single statement. Using a CTE, you can group your results by a derived column.
I have written previously about what I call atomic and molecular queries; atomic queries address one table, while molecular queries are built up from the atoms providing clarity and reusability. Using CTEs, you can do the same thing. You can isolate parts of the query into readable "chunks" and then build up a complex query from the chunks. The most significant and powerful thing you can do with a CTE is perform a recursive query.
Creating a CTE
A CTE is created by using the keyword WITH. The template is:
WITH CTE_name[ (column_name [,...n] ) ]
AS
( CTE_query_specification )
If the column names mentioned in the CTE definition are unique, then you don't need to name them. However, naming them also lets you give them new column names.
Here is an example that uses the AdventureWorks sample database included with SQL Server 2005. This database is highly normalized and, as a result, requires several joins to assemble the information concerning employees. Views simplify this, but also gather all the information regarding employees, and you may only require some of it.
The data regarding employees of AdventureWorks is distributed among several tables. This is further complicated by the fact that employees and managers are both stored in a single table (HumanResources.Employee), while their names (and other data) are stored in the Person.Contact table.
First, let's create a CTE that retrieves the employee name:
WITH cte_Employee
AS
(
SELECT e.EmployeeID, c.FirstName, c.MiddleName, c.LastName,
e.Title AS JobTitle, c.Phone, e.ManagerID
FROM HumanResources.Employee AS e
INNER JOIN Person.Contact AS c ON c.ContactID = e.ContactID
)
Then, we can select one or more columns from the CTE as if it were a standard table or view.
Let's up the ante a little. We want the names of the employees and their managers, so we'll use the CTE twice, joining it to itself. Here is the complete query:
WITH cte_Employee
AS
(
SELECT e.EmployeeID, c.FirstName, c.MiddleName, c.LastName,
e.Title AS JobTitle, c.Phone, e.ManagerID
FROM HumanResources.Employee AS e
INNER JOIN Person.Contact AS c ON c.ContactID = e.ContactID
)
SELECT E.FirstName + ' ' E.LastName Employee,
M.FirstName + ' ' M.LastName Manager
FROM cte_Employee AS E
LEFT OUTER JOIN cte_Employee AS M
ON E.ManagerID = M.EmployeeID
One proviso: You cannot create two CTEs within a single statement.
Summary
CTEs are a powerful and slick new feature in SQL Server 2005. They make your SQL Server more readable and easier to maintain, masking the complexity of tricky queries. As shown here, you can use a CTE more than once within a SQL Server statement.
In my next tip, I will show you how to use this capability to perform a recursive query, such as you might find in a bill-of-materials application.
Miss a tip?
Check out the SQL Server archive, and catch up on the most recent editions of Arthur Fuller's column.
Print/View all Posts Comments on this article
|
|
|
|
|
|
White Papers, Webcasts, and Downloads
- Building the Virtualized Enterprise with VMware Infrastructure VMware This paper explains how adopting a virtual infrastructure -- comprised of server, storage, and networking virtualization technologies -- can help your organization build a sustainable competitive ... Download Now
- VMware Infrastructure: A Guide to Bottom-Line Benefits VMware Frustrated by the high cost of maintaining or building ever-larger data centers? Get the facts you need to formulate your Virtualization Action Plan. Download Now
- Why Isn't Server Virtualization Saving Us More? A Few Small Changes May Dramatically Increase Your Efficiency VMware Ever wonder why your company isn't saving more from its server virtualization? Making a few small changes could dramatically increase your efficiency. Download Now
- Five Steps to Determine When to Virtualize YourServers VMware Thinking of virtualizing the servers at your company? Use this step-by-step guide to determine when's the best time to make your big move. Download Now
- The Impact of Virtualization Software on Operating Environments VMware Today's use of virtualization technology allows IT professionals to ... Download Now
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

