0% encontró este documento útil (0 votos)
102 vistas8 páginas

Guia 04 - Funciones en SQL Server

Este documento presenta una guía para el uso de funciones en Transact-SQL. Incluye seis ejercicios para crear diferentes tipos de funciones escalares, inline table-valued, multi-statement table-valued y personalizadas utilizando la base de datos AdventureWorks. Los ejercicios muestran cómo crear las funciones y cómo utilizarlas en consultas SELECT y WHERE.

Cargado por

Ricardo Castillo
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
102 vistas8 páginas

Guia 04 - Funciones en SQL Server

Este documento presenta una guía para el uso de funciones en Transact-SQL. Incluye seis ejercicios para crear diferentes tipos de funciones escalares, inline table-valued, multi-statement table-valued y personalizadas utilizando la base de datos AdventureWorks. Los ejercicios muestran cómo crear las funciones y cómo utilizarlas en consultas SELECT y WHERE.

Cargado por

Ricardo Castillo
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 8

Guía 04.

Uso de funciones
Curso: Consultas avanzadas de datos con Transact-SQL
Tiempo de ejecución: 2 horas

I. AMBIENTE DE LABORATORIO

Para esta práctica se conectará al servidor con los siguientes parámetros:

Host: 162.248.53.71
Base de datos: AdventureWorks2014

Usuario: capacitacion
Password: Nuevo1010$

II. DESARROLLO

Ejecutar el siguiente script para actualizar el ambiente de pruebas de la base


AdventureWorks

UPDATE Sales.SpecialOffer
SET StartDate = DateAdd(day, -1, GetDate()),
EndDate = DateAdd(day, 27, GetDate())
WHERE SpecialOfferId IN (1,3,5,7,9,11,13,15)

UPDATE Sales.SpecialOffer
SET StartDate = DateAdd(day, 28, GetDate()),
EndDate = DateAdd(month, 2, GetDate())
WHERE SpecialOfferId IN (2,4,6,8,10,12,14,16)
GO

Ejercicio 1:
Creando funciones escalares en SQL Server

❑ Conéctese al Sql Server Managment Studio


❑ En el explorador de objetos, expanda las funciones escalares creadas en la
base de datos AdventureWorks (Programmabillity -> Functions -> Scalar –
Valued Funtions)
❑ Ejecute el siguiente script para crear la función

1
-- Create scalar function
CREATE FUNCTION Production.GetAverageRatingForProduct_GX (@ProductID int)
RETURNS int
AS
BEGIN
DECLARE @Average int

SELECT @Average = AVG(Rating)


FROM Production.ProductReview
WHERE ProductID = @ProductId
GROUP BY ProductID

IF (@Average IS NULL)
SET @Average = 0

RETURN @Average
END
GO

❑ Refresque la sección de funciones de la base Adventureworks e identifique


la función que acaba de crear.
❑ Ejecute el siguiente script para utilizar la función creada anteriormente en
una condición SELECT:

SELECT ProductID,
Name,
Production.GetAverageRatingForProduct_GX(ProductID) AS
Average
FROM Production.Product
ORDER BY ProductID
GO

❑ Comente el script anterior, colocando la explicación de la función ejecutada

❑ Ejecute el siguiente script para utilizar la función creada anteriormente en


una condición WHERE:

-- Test scalar function in WHERE


SELECT ProductID,
Name,
Production.GetAverageRatingForProduct_GX(ProductID) AS
Average
FROM Production.Product
WHERE Production.GetAverageRatingForProduct_GX (ProductID) > 0
ORDER BY ProductID
GO

❑ Comente el script anterior, colocando la explicación la función anterior


(¿Que hace la función ejecutada?)

2
Ejercicio 2:
Creando funciones inline table-valued en SQL Server

❑ En el explorador de objetos, expanda las funciones escalares creadas en la


base de datos AdventureWorks (Programmabillity -> Functions -> Table –
Valued Functions)
❑ Ejecute el siguiente script para crear la función:

-- Create inline function


CREATE FUNCTION Production.GetReviewsForProduct_GX (@ProductID int)
RETURNS TABLE
AS
RETURN (
SELECT Name,
ReviewDate,
ReviewerName,
Rating,
Comments
FROM Production.ProductReview Review
INNER JOIN Production.Product Product ON
Product.ProductID = Review.productid
WHERE Review.ProductID = @ProductID)
)

❑ Refresque la sección de funciones de la base Adventureworks e identifique


la función que acaba de crear.
❑ Ejecute el siguiente script para utilizar la función creada anteriormente en
una condición SELECT:

-- Test inline function


SELECT * FROM Production.GetReviewsForProduct_GX(937);
GO

❑ Comente el script anterior, colocando la explicación de la función ejecutada

3
Ejercicio 3:
Creando funciones multi-statement table-valued en SQL Server

❑ Ejecute el siguiente script para crear la función:

-- Create multi-statement function


CREATE FUNCTION Production.GetReviewDetail_GX
(@format char(8))
RETURNS @tbl_reviews TABLE
(ProductName nvarchar(50), Rating int, Comment nvarchar(3850))
AS
BEGIN
IF (UPPER(@format) = 'POSITIVE')
INSERT @tbl_reviews
SELECT Name,
Rating,
Comments
FROM Production.ProductReview Review
INNER JOIN Production.Product Product ON
Product.ProductID = Review.productid
WHERE Rating > 2
ORDER BY Name, Rating
ELSE IF (UPPER(@format) = 'NEGATIVE')
INSERT @tbl_reviews
SELECT Name,
Rating,
Comments
FROM Production.ProductReview Review
INNER JOIN Production.Product Product ON
Product.ProductID = Review.productid
WHERE Rating <= 2
ORDER BY Name, Rating
RETURN
END
GO

❑ Refresque la sección de funciones de la base Adventureworks e identifique


la función que acaba de crear.
❑ Ejecute el siguiente script para utilizar la función creada anteriormente en
una condición SELECT:

-- Test multi-statement function


SELECT * FROM Production.GetReviewDetail_GX('positive');
SELECT * FROM Production.GetReviewDetail_GX('negative');
GO

❑ Comente el script anterior, colocando la explicación de la función ejecutada

4
Ejercicio 4:
Creando funciones personalizadas

❑ Ejecute el siguiente script para crear la función


GetMaximumDiscountForCategory:
-- Create Sales.GetMaximumDiscountForCategory
CREATE FUNCTION Sales.GetMaximumDiscountForCategory_GX (@Category
nvarchar(50))
RETURNS smallmoney
AS
BEGIN
DECLARE @Max smallmoney

SELECT @Max = MAX(DiscountPct)


FROM Sales.SpecialOffer
WHERE Category = @Category
GROUP BY Category

IF (@Max IS NULL)
SET @Max = 0

RETURN @Max
END
GO
❑ Ejecute el siguiente script para utilizar la función creada anteriormente:

-- Test Sales.GetMaximumDiscountForCategory
SELECT Sales.GetMaximumDiscountForCategory_GX ('Reseller');
GO

❑ Comente el script de creación, colocando una breve explicación de la


función realizada y el tipo de función desarrollada

5
Ejercicio 5:
Creando funciones personalizadas

❑ Ejecute el siguiente script para crear la función GetDiscountsForDate:

-- Create Sales.GetDiscountsForDate
CREATE FUNCTION Sales.GetDiscountsForDate_GX (@DateToCheck datetime)
RETURNS TABLE
AS
RETURN (
SELECT Description,
DiscountPct,
Type,
Category,
StartDate,
EndDate,
MinQty,
MaxQty
FROM Sales.SpecialOffer
WHERE @DateToCheck BETWEEN StartDate AND EndDate
)
GO

❑ Ejecute el siguiente script para utilizar la función creada anteriormente:

-- Test Sales.GetDiscountsForDate
SELECT *
FROM Sales.GetDiscountsForDate_GX (GetDate())
ORDER BY DiscountPct DESC;
GO

❑ Comente el script de creación, colocando una breve explicación de la


función realizada y el tipo de función desarrollada

6
Ejercicio 6:
Creando funciones personalizadas

❑ Ejecute el siguiente script para crear la función GetDiscountedProducts


-- Create Sales.GetDiscountedProducts
CREATE FUNCTION Sales.GetDiscountedProducts_GX
(@IncludeHistory bit)
RETURNS @tbl_products TABLE
(ProductID int,
Name nvarchar(50),
ListPrice money,
DiscountDescription nvarchar(255),
DiscountPercentage smallmoney,
DiscountAmount money,
DiscountedPrice money)
AS
BEGIN
IF (@IncludeHistory = 1)
INSERT @tbl_products
SELECT P.ProductID,
P.Name,
P.ListPrice,
SO.Description,
SO.DiscountPct,
P.ListPrice * SO.DiscountPct,
P.ListPrice - P.ListPrice * SO.DiscountPct
FROM Sales.SpecialOfferProduct SOP INNER JOIN
Sales.SpecialOffer SO ON SOP.SpecialOfferID =
SO.SpecialOfferID INNER JOIN
Production.Product P ON SOP.ProductID =
P.ProductID
WHERE (SO.DiscountPct > 0)
ORDER BY ProductID
ELSE
INSERT @tbl_products
SELECT P.ProductID,
P.Name,
P.ListPrice,
SO.Description,
SO.DiscountPct,
P.ListPrice * SO.DiscountPct,
P.ListPrice - P.ListPrice * SO.DiscountPct
FROM Sales.SpecialOfferProduct SOP INNER JOIN
Sales.SpecialOffer SO ON SOP.SpecialOfferID =
SO.SpecialOfferID INNER JOIN
Production.Product P ON SOP.ProductID =
P.ProductID
WHERE (SO.DiscountPct > 0) AND GetDate() BETWEEN StartDate
AND EndDate
ORDER BY ProductID
RETURN
END
GO

7
❑ Ejecute el siguiente script para utilizar la función creada anteriormente:

-- Test Sales.GetDiscountedProducts
SELECT * FROM Sales.GetDiscountedProducts_GX(0);
SELECT * FROM Sales.GetDiscountedProducts_GX(1);
GO

❑ Comente el script de creación, colocando una breve explicación de la


función realizada y el tipo de función desarrollada

Ejercicio 7:
Implementando funciones

Cree las siguientes funciones, seleccione un tipo para cada una e incorpore la
llamada a la función con la información que usted crea conveniente:
❑ Función para retornar el numero de empleados por departamento
❑ Función para retornar los datos de las ordenes de compras por fecha
❑ Función para obtener los datos principales de los empleados por
departamento

También podría gustarte