USE AdventureWorks2016CTP3;
GO
-- Exemplo 1: procedure que devolve os resultados por OUT parameters
CREATE PROCEDURE dbo.up_Medias1
(
@PrimeiroDoMes date,
@MediaSubTotal money OUT,
@MediaTaxAmt money OUT,
@MediaFreight money OUT
)
AS
IF DATEPART(DAY, @PrimeiroDoMes) <> 1
RAISERROR(N'@PrimeiroDoMes dia deve ser 1.', 12, 1);
SELECT @MediaSubTotal = AVG(SubTotal), @MediaTaxAmt = AVG(TaxAmt), @MediaFreight = AVG(Freight)
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN @PrimeiroDoMes AND EOMONTH(@PrimeiroDoMes);
GO
-- Testar o procedure
DECLARE @PrimDoMes date = N'2014-01-01';
DECLARE @MedSubTotal money;
DECLARE @MedTaxAmt money;
DECLARE @MedFreight money;
EXEC dbo.up_Medias1 @PrimDoMes, @MedSubTotal OUTPUT, @MedTaxAmt OUTPUT, @MedFreight OUTPUT;
-- Apresentar os resultados
SELECT @MedSubTotal AS 'Media SubTotal', @MedTaxAmt AS 'Media TaxAmt', @MedFreight AS 'Media Freight';
-- Exemplo 2: procedure que devolve os resultados por result set
CREATE PROCEDURE dbo.up_Medias2
(
@PrimeiroDoMes date
)
AS
IF DATEPART(DAY, @PrimeiroDoMes) <> 1
RAISERROR(N'@PrimeiroDoMes dia deve ser 1.', 12, 1);
SELECT AVG(SubTotal) AS 'MediaSubTotal', AVG(TaxAmt) AS 'MediaTaxAmt', AVG(Freight) AS 'MediaFreight'
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN @PrimeiroDoMes AND EOMONTH(@PrimeiroDoMes);
GO
-- Testar o procedure
DECLARE @PrimDoMes date = N'2014-01-01';
EXEC dbo.up_Medias2 @PrimDoMes;
-- Exemplo 4: function que devolve medias por 12 meses
CREATE FUNCTION dbo.fn_Medias4
(
@Ano int
)
RETURNS TABLE
AS
RETURN (SELECT YEAR(OrderDate) AS 'Ano', MONTH(OrderDate) AS 'Mês', AVG(SubTotal) AS 'MediaSubTotal', AVG(TaxAmt) AS 'MediaTaxAmt', AVG(Freight) AS 'MediaFreight'
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN DATEFROMPARTS(@Ano, 1, 1) AND DATEFROMPARTS(@Ano, 12, 31)
GROUP BY YEAR(OrderDate), MONTH(OrderDate));
GO
-- Testar o function
SELECT *
FROM dbo.fn_Medias4(2013)
ORDER BY Ano, Mês;
GO