Generics CTE SQL Delegate
Generics CTE SQL Delegate
Generics allow you to realize type safety at compile time. They allow
you to create a data structure without committing to a specific data
type. When the data structure is used, however, the compiler makes
sure that the types used with it are consistent for type safety. Generics
provide type safety, but without any loss of performance or code bloat.
While they are similar to templates in C++ in this regard, they are very
different in their implementation. Generic classes encapsulate
operations that are not specific to a particular data type. The most
common use for generic classes is with collections like linked lists,
hash tables, stacks, queues, trees and so on where operations such as
adding and removing items from the collection are performed in much
the same way regardless of the type of data being stored.
CTE are one of the beautiful and the most powerful feature of SQL
Server. It is introduced in SQL Server 2005 and I guess is one of the
best things in SQL Server. This not only simplifies most of the complex
and impossible queries in T-SQL, but also provides one medium to deal
with recursive queries. Moreover, I can say it is mainly for recursive
queries. It can be used in replacement of derived tables (sub queries),
temp tables, table variables, inline user-defined functions etc. The
Common Table Expression (CTE) is called as a temporary named
RESULT SET, within the scope of an executing statement that can be
used within a SELECT, INSERT, UPDATE, or DELETE or even in a
CREATE VIEW or MERGE statement.
Here the Ordered Customers will be placed in the CTE result set and it
will be joined with the Customers details.
WITH MyCTE1
AS
(
SELECT ProductID, SupplierID, CategoryID, UnitPrice, ProductName
FROM Products
),
MyCTE2
AS
(
SELECT DISTINCT ProductID FROM "Order Details"
)
SELECT C1.ProductID,C1.ProductName,C1.SupplierID,C1.CategoryID
FROM MyCTE1 C1 INNER JOIN MyCTE2 C2 ON C1.ProductID =
C2.ProductID
Here, there are two result sets that will be filtered based on the join
condition.
WITH PartProdCateSale
AS
(
SELECT ProductID FROM Products WHERE CategoryID = (SELECT
CategoryID FROM Categories WHERE CategoryName='Condiments')
UNION ALL
SELECT ProductID FROM Products WHERE CategoryID = (SELECT
CategoryID FROM Categories WHERE CategoryName='Seafood')
)
SELECT OD.ProductID,SUM(OD.UnitPrice*OD.Quantity) AS [Total Sale]
FROM "Order Details" OD INNER JOIN PartProdCateSale PPCS ON
PPCS.ProductID = OD.ProductID
GROUP BY OD.ProductID
Normally when we combine the many result sets we create table and
then insert into that table. But see here, we have combined with the
union all and instead of table, here CTE has used.
CTE 6: CTE with identity column
WITH MyCustomCTE
AS
(
SELECT CustomerID, row_number () OVER (ORDER BY CustomerID)
AS iNo FROM
Customers
)
SELECT * FROM MyCustomCTE
Lambda expression can be broken down into parameters followed by execution code.