#0319 – SQL Server – CTE and UNION


I was recently asked a very interesting question at work. Someone wanted to use the same CTE in two queries the results of which were to be combined using the UNION clause. I was approached to see whether it was feasible.

In order to work out the feasibility, I simply carried out a quick PoC which I am sharing today. It is quite possible to use the same CTE in two queries which are combined via UNION.

USE tempdb;
GO
;WITH EmployeeListCTE (BusinessEntityId, IsCurrent)
AS (SELECT el.BusinessEntityId,
           el.IsCurrent
    FROM (VALUES (1, 1),
                 (2, 0),
                 (3, 1),
                 (4, 1),
                 (5, 1)
         ) AS el(BusinessEntityId, IsCurrent)
   )
SELECT elCTE.BusinessEntityId,
       elCTE.IsCurrent
FROM EmployeeListCTE AS elCTE 
WHERE elCTE.IsCurrent = 1
UNION
SELECT elCTE.BusinessEntityId,
       elCTE.IsCurrent
FROM EmployeeListCTE AS elCTE 
WHERE elCTE.IsCurrent = 0;
GO

/* RESULTS
----------------+-----------
BusinessEntityId|IsCurrent
----------------+-----------
1               |1
3               |1
4               |1
5               |1
2               |0
*/

References:

  • Common Table Expressions (CTE) [Link]
  • Interesting enhancements to the VALUES Clause in SQL Server 2008 [Link] (by Madhivanan (B|T))

Until we meet next time,

Be courteous. Drive responsibly.

Advertisements

Let me know what you think about this post by leaving your feedback here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s