0% found this document useful (0 votes)
17 views

SQLDEV320A WEEK7-2

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

SQLDEV320A WEEK7-2

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Instructor:

SQL Server boB Taylor


Developme [email protected]
nt m
SQLDEV
320 A
Spring
2021 MCA, MCM, MCSM,
Week 7 MCSE, MCSD, MCT,
Data Scientist
REVIEW
• RECAP WEEK6

TODAY OUTPUT CLAUSE

MERGE

PIVOT / UNPIVOT

RECURSIVE QUERIES

USING WINDOWING FUNCTIONS

PARTITIONING

CLR
OUTPUT Clause

Returns information from each row


affected by an INSERT, UPDATE, DELETE,
or MERGE statement

DECLARE @rows table([CultureID] nchar(6), [Name]


nvarchar(50), [ModifiedDate] datetime);

BEGIN TRAN;
DELETE [Production].[Culture] OUTPUT DELETED.* INTO
@rows;
ROLLBACK TRAN;
OUTPUT Clause

DEMO
MERGE statement

Runs insert, update, or delete operations


on a target table from the results of a join
with a source table. For example,
synchronize two tables by inserting,
updating, or deleting rows in one table
based on differences found in the other
table.

Merge Statement Reference


MERGE statemetn

DEMO
PIVOT \ UNPIVOT
YEAR QUARTER Sales
2014 1 14373277.4766
2013 3 14339319.1851
2011 3 5647550.6633
2011 4 7434031.4429
2014 2 8046220.8391
2013 1 8771886.3577
2012 2 9935495.1729
2013 4 13629621.0374
2012 3 10164406.8281
2011 2 1074117.4188
2013 2 12225061.383
2012 1 9443736.8161
2012 4 8132061.4949

YEAR Q1 Q2 Q3 Q4
2011 NULL 1074117.4188 5647550.6633 7434031.4429
2012 9443736.8161 9935495.1729 10164406.8281 8132061.4949
2013 8771886.3577 12225061.383 14339319.1851 13629621.0374
2014 14373277.4766 8046220.8391 NULL NULL
Pivot / Unpivot
operator
DEMO
In order to understand recursion, you must first understand recursion

Recursion
Recursion occurs when a thing is defined in terms of itself or of its
type.

Recursion is used in a variety of disciplines ranging from linguistics to


logic.

The most common application of recursion is in mathematics and


computer science, where a function being defined is applied
within its own definition. While this apparently defines an infinite
number of instances (function values), it is often done in such a
way that no loop or infinite chain of references can occur.
Recursive
CTEs
USE [AdventureWorks2019];
GO

WITH FACTORIAL( num,fact) AS


(
SELECT 0, 1 UNION ALL
SELECT 1, 1 UNION ALL
SELECT num+1, fact * (num+1)
FROM FACTORIAL F WHERE num < 12
)
SELECT num, fact FROM FACTORIAL WHERE NUM <= 10;
Recursive CTEs
Network Hierarchy Representation
Graph
Recursive CTEs
Hierarchy Representation Hierarchy
Expanded
Recursive CTEs
WITH EmployeeHierarchy (EmployeeId, ManagerId)
AS (SELECT E.[BusinessEntityID] AS [EmployeeId],
M.[BusinessEntityID] AS [ManagerId]
FROM [HumanResources].[Employee] AS E
LEFT JOIN [HumanResources].[Employee] AS M
ON E.[OrganizationNode].Getancestor(1) = M.[OrganizationNode]),
EmployeeHierarchyExploded (EmployeeId, ManagerId, OrganizationLevel, HierarchyPath)
AS (SELECT EmployeeId,
ManagerId,
1 AS [OrganizationLevel],
Format(EmployeeId, '0000') AS [HierarchyPath]
FROM EmployeeHierarchy
WHERE ManagerId IS NULL
UNION ALL
SELECT E.EmployeeId,
E.ManagerId,
OrganizationLevel + 1,
HierarchyPath + '.'
+ Format(E.EmployeeId, '0000')
FROM EmployeeHierarchy E
JOIN EmployeeHierarchyExploded H
ON E.ManagerId = H.EmployeeId)
SELECT *
FROM EmployeeHierarchyExploded
ORDER BY HierarchyPath
17
Recursion using Stored Procedure
USE tempdb;
go
CREATE PROCEDURE dbo.Sp_factorial(@pNumber INT)
AS
BEGIN
DECLARE @iNum INT,
@tResult INT
IF @pNumber > 1
BEGIN
SELECT @iNum = @pNumber - 1;
EXEC @tResult = Sp_factorial @iNum
SET @tResult = @pNumber * @tResult;
END
ELSE
SET @tResult = 1;
RETURN @tResult
END
GO

DECLARE @Fact6 INT


EXEC @Fact6 = dbo.Sp_factorial 6
PRINT @Fact6

12
Recursion

DEMO
OVER Clause Overview
Determines the partitioning and ordering of a rowset before the associated
window function is applied.

That is, the OVER clause defines a window or user-specified set of rows within
a query result set. A window function then computes a value for each row in
the window.
You can use the OVER clause with functions to compute aggregated values
such as moving averages, cumulative aggregates, running totals, or a top N
per group results.

Over clause reference


Window Functions Overview
Window
RESULTS
specification
PARTITION BY
ORDER BY

Aggregate
WINDOW Specification
Functions OVER(
COUNT
- PARTITION BY<column>
SUM - ORDER BY <column>
- ROWS <number>
AVERAGE
- RANGE <values>
Ranking
Functions
ROW_NU
MBER
RANK
Analytic
DENSE_RANK
Functions
NTILE
LAG
LEAD
FIRST_VALUE
Introduction to Window Functions
OVER clause
PARTITION
ORDER BY
SELECT p.LastName,
s.SalesYTD,
a.PostalCode,
Row_number()
OVER(PARTITION BY PostalCode
ORDER BY SalesYTD DESC ) AS [ROW NUMBER]
FROM Sales.SalesPerson AS s
INNER JOIN Person.Person AS p
ON s.BusinessEntityID =
p.BusinessEntityID
INNER JOIN Person.Address AS a
ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL
AND SalesYTD <> 0
ORDER BY PostalCode;
GO
Windows Functions Overview
Window
RESULTS
specification
PARTITION BY
ORDER BY
COUNT
WINDOW Specification
Aggregate OVER(
Functions
SUM - PARTITION BY<column>
AVERAGE - ORDER BY <column>
- ROWS <number>
Ranking - RANGE <values>
Functions
ROW_NUMBER
RANK
DENSE_RANK
NTILE
Analytic
Functions
LAG
LEAD
FIRST_VALUE
Introduction to Window Functions
With aggregate functions:
Using SUM

SELECT YEAR([OrderDate]) AS [Year]


, DATEPART(WEEK,[OrderDate]) AS [Week]
, [SalesOrderID]
, [SubTotal] [Order Subtotal]
, SUM([SubTotal])
OVER(PARTITION BY
YEAR([OrderDate]),DATEPART(WEEK,[OrderDate])
) AS [Weekly Total]
, ([SubTotal] /SUM([SubTotal])
OVER(PARTITION BY YEAR([OrderDate]), DATEPART(WEEK,
[OrderDate]))) * 100 AS [Pct of Week]
FROM [Sales].[SalesOrderHeader]
ORDER BY YEAR([OrderDate]), DATEPART(WEEK,
[OrderDate]), [Pct of Week] DESC;
Windows Functions Overview
Window
RESULTS
specification
PARTITION BY
ORDER BY
WINDOW Specification
Aggregate OVER(
Functions - PARTITION BY<column>
COUNT - ORDER BY <column>
SUM
- ROWS <number>
- RANGE <values>
AVERAGE
ROW_NUMBER
Ranking
RAN
K
Functions
DENSE_RAN
K
NTILE

Analytic
Functions
LAG
LEAD
FIRST_VALUE
Introduction to Window Functions
With ranking functions:
Using NTILE
SELECT Year([OrderDate]) AS [Year],
[SalesOrderID],
[SubTotal] AS [Order Subtotal],
Ntile(100)
OVER(
PARTITION BY Year([OrderDate])
ORDER BY [SubTotal] ) AS [Percentile
Rank]
FROM [Sales].[SalesOrderHeader]
ORDER BY Year([OrderDate]),
[Percentile Rank],
[SubTotal] ;

Defintion of Percentile
Windows Functions Overview
Window
RESULTS
specification
PARTITION BY
ORDER BY
WINDOW Specification
Aggregate OVER(
Functions - PARTITION BY<column>
COUNT - ORDER BY <column>
SUM
- ROWS <number>
- RANGE <values>
AVERAGE

Ranking
Functions
ROW_NU
MBER
RANK
DENSE_RANK
LEAD
NTILE
FIRST_VALUE
Analytic
LAST_VALUE
Functions
Introduction to Window Functions
With analytic
functions:
Using LAG

WITH YearQuarterSalesSummary
AS (SELECT Year([OrderDate]) AS [Year],
Datepart(QUARTER, [OrderDate]) AS [Quarter],
Sum([SubTotal]) AS
[CurrentQuarterSales]
FROM [Sales].[SalesOrderHeader]
GROUP BY Year([OrderDate]),
Datepart(QUARTER, [OrderDate]))
SELECT [Year],
[Quarter],
Lag([CurrentQuarterSales], 1, NULL)
OVER (
ORDER BY[Year], [Quarter]) AS [PreviousQuarterSales]
FROM YearQuarterSalesSummary
ORDER BY [Year],
[Quarter] ASC ;
Windowing Options Matrix
R-Required, O-Optional, X-Not
Allowed
Common Language Routine (CLR)
You can build database objects using the SQL Server integration with
the .NET Framework common language runtime (CLR). Managed code that
runs inside of Microsoft SQL Server is referred to as a "CLR routine.“

These routines Scalar-valued user-defined functions (scalar UDFs)


include:
Table-valued user-defined functions (TVFs)
User-defined procedures (UDPs)
User-defined triggers
The system.data.dll System.Data
assembly contains
the following System.Data.Sql
namespaces, which
are required for Microsoft.SqlServer.Server
compiling CLR System.Data.SqlTypes
database objects:
Common Language Runtime (CLR)

01 02 03 04 05
Enable CLR in Have a class Map each CLR Register Invoke the
the database with public method to a assembly in stored
(once for the static methods function or database procedure
instance) stored from SQL
procedure
Steps to create a scalar CLR
function
1) Configure SQL Server

sp_configure 'show advanced


options', 1; GO
RECONFIGURE;
GO
sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO

3
4
Steps to create a scalar CLR
function
3) Register the assembly and UDF
CREATE ASSEMBLY FirstUdf FROM
'FirstUdf.dll';
GO
CREATE FUNCTION CountSalesOrderHeader()
RETURNS INT AS EXTERNAL NAME
FirstUdf.T.ReturnOrderCount;
GO
SELECT dbo.CountSalesOrderHeader();
GO
Mapping CLR Parameter Data

3
5
Mapping
CLR
Paramete
r Data

Full Reference
Week 7 Assignment

QUIZ 7 CODING
ASSIGNMENT

You might also like