Common Table Expressions (CTE), doing wonders.


What is Common Type Expressions? and How do we use it in our Stored Procedures?

Common Type Expressions is almost similar to a view but you don't really create a physical view, instead you are querying a result set that is available for your SELECT, UPDATE, DELETE statements.

Here's an example using Northwind:


We may have a query like this:

SELECT CustomerID, 
       CompanyName, 
       CONVERT(varchar,OrderDate,101) as OrderDate, 
       ProductName, 
       Quantity
FROM ( SELECT c.CustomerID,c.CompanyName, o.OrderDate, 
              p.ProductName, od.Quantity
FROM Orders o
INNER JOIN dbo.Customers c ON o.CustomerID = c.CustomerID
INNER JOIN dbo.[Order Details] od ON o.OrderID =  od.OrderID
INNER JOIN dbo.Products p ON od.ProductID = p.ProductID
) details
WHERE details.Quantity>10

With CTE we can do it like this:
WITH details_CTE(CustomerID,CompanyNameOrderDate, ProductName, Quantity)AS(      SELECT c.CustomerID, c.CompanyName, o.OrderDate, p.ProductName, 
             od.Quantity
      FROM Orders o
      INNER JOIN dbo.Customers c ON o.CustomerID = c.CustomerID
      INNER JOIN dbo.[Order Details] od ON o.OrderID =  od.OrderID
      INNER JOIN dbo.Products p ON od.ProductID = p.ProductID
SELECT CustomerID, CompanyName, 
       CONVERT(varchar,OrderDate,101) as OrderDate, ProductName, 
       Quantity 
From  details_CTE
you see we've created the first part which is the CTE similar to a view with can be queried later in our select statements. Looking at the example, we can actually create a nested CTE.



Comments

Popular posts from this blog

Serializing JSON string to ExpandoObject

XML to ExpandoObject using Recursion in C#

Automatically Discover and Assign Parameter with Values to a Stored Procedure Call in C#