Está en la página 1de 6

UNIVERSIDAD NACIONAL DE TRUJILLO Base de datos Avanzadas

LABORATORIO Nº 03
PROGRAMACIÓN DE FUNCIONES DE TABLAS

1. FUNCIÓN PARA OBTENER LA CANTIDAD AGREGADA DE UN PRODUCTO

USE AdventureWorks2012
go
if OBJECT_ID ('dbo.fnCanStockInventario', 'FN') is not null
drop function dbo.fnCanStockInventario
go
create function dbo.fnCanStockInventario(@ProductID int)
returns int
AS
-- devolver Stock para el producto
Begin
declare @ret int
select @ret = SUM(P.quantity)
from Production.ProductInventory P
where P.ProductID = @ProductID
and P.LocationID = '6'
if (@ret is null)
SET @ret = 0
return @ret
End
go

-- Ejecución de la función dbo.fnCanStockInventario para devolver la cantidad de


-- inventario actual de aquellos productos que tienen un ProductModelID entre 75 y 80
USE AdventureWorks2012
go
select ProductModelID as 'Id Modelo de Producto',
Name as Producto,
dbo.fnCanStockInventario(productID) as 'Unidades en Stock'
from Production.Product
where ProductModelID between 75 and 80;
go

DR. LUIS BOY CHAVIL Página 1


UNIVERSIDAD NACIONAL DE TRUJILLO Base de datos Avanzadas

2. FUNCIONES DE TABLA EN LÍNEA

-- Función para obtener los agregados de las ventas hasta la fecha como venta total para cada
-- producto vendido en el almacen

USE AdventureWorks2012
go
if OBJECT_ID ('sales.fnVentasporAlmacen', 'FN') is not null
drop function sales.fnVentasporAlmacen
go
create function sales.fnVentasporAlmacen(@Storeid int)
returns table
AS
return
( select P.ProductID, P.Name, SUM(SD.LineTotal) as 'Venta Total'
from Production.Product as P
join sales.salesOrderDetail as SD
on SD.ProductID=P.ProductID
join Sales.SalesOrderHeader as SH
on SH.SalesOrderID = SD.SalesOrderID
where SH.CustomerID = @StoreID
group by P.ProductID, P.Name
)
go

-- Ejecutamos con ID del cliente '29565'

USE AdventureWorks2012
go
select * from sales.fnVentasporAlmacen (29565)

DR. LUIS BOY CHAVIL Página 2


UNIVERSIDAD NACIONAL DE TRUJILLO Base de datos Avanzadas

3. FUNCIONES DE TABLA DE MÚLTIPLES SENTENCIAS

-- Cambio de la columna de una variable


USE AdventureWorks2012
go
if OBJECT_ID ('HumanResources.fnNombreEmpleados', 'FN') is not null
drop function HumanResources.fnNombreEmpleados
go
create function HumanResources.fnNombreEmpleados(@formato nvarchar(15))
returns @TablaEmpleados TABLE
(EmployeeID int primary key, [Employee Name] nvarchar(100))
AS
Begin
if (@formato = 'Nombre Corto')
INSERT @TablaEmpleados
select vE.BusinessEntityID,
LastName
from HumanResources.vEmployee vE
else if (@formato = 'Nombre Completo')
INSERT @TablaEmpleados
select vE.BusinessEntityID,
(Firstname+' '+Lastname)
from HumanResources.vEmployee vE
return
END
go

-- Ahora, ejecutaremos la función de dos formas:


-- Forma1:
USE AdventureWorks2012
go
select * from HumanResources.fnNombreEmpleados('Nombre Corto')

-- Forma2:
USE AdventureWorks2012
go
select * from HumanResources.fnNombreEmpleados('Nombre Completo')

DR. LUIS BOY CHAVIL Página 3


UNIVERSIDAD NACIONAL DE TRUJILLO Base de datos Avanzadas

4. Creación de tabla Productos de una categoría establecida en


parámetro

use AdventureWorks2012
go
if OBJECT_ID ('fnProductosEnCateg', 'FN') is not null
drop function fnProductosEnCateg
go
create function fnProductosEnCateg(@Categoria varchar(50))
returns @Productos table(ProductID int primary key,
Producto varchar(50), ProductLine char(02),
Categoria varchar(50))
AS
Begin
Insert @Productos select P.ProductID, P.Name, P.ProductLine, K.Name
from Production.Product P
inner join Production.ProductCategory K
on P.ProductSubCategoryID=K.ProductCategoryID
where K.Name=@Categoria
return
end
go

--Mostrar resultados de productos de la categoría 'Bikes'

select *
from dbo.fnProductosEnCateg('Bikes')

5. Funciones de tablas
USE [AdventureWorks2012]
GO
USE AdventureWorks2012
go
if OBJECT_ID ('[dbo].[ufnGetContactInformation]', 'FN') is not null
drop function [dbo].[ufnGetContactInformation]
go

DR. LUIS BOY CHAVIL Página 4


UNIVERSIDAD NACIONAL DE TRUJILLO Base de datos Avanzadas

create function [dbo].[ufnGetContactInformation](@PersonID int)


RETURNS @retContactInformation TABLE
(
[PersonID] int NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[JobTitle] [nvarchar](50) NULL,
[BusinessEntityType] [nvarchar](50) NULL
)
AS
-- Retorna el primer nombre, apellidos y título de trabajo más tipo de entrada
-- de negocio para el contacto especificado.

-- Desde un contacto puede servir para múltiples funciones, más de una fila puede
-- ser devuelto.
BEGIN
IF @PersonID IS NOT NULL
BEGIN
IF EXISTS(SELECT * FROM [HumanResources].[Employee] e
WHERE e.[BusinessEntityID] = @PersonID)
INSERT INTO @retContactInformation
SELECT @PersonID, p.FirstName, p.LastName, e.[JobTitle], 'Employee'
FROM [HumanResources].[Employee] AS e
INNER JOIN [Person].[Person] p
ON p.[BusinessEntityID] = e.[BusinessEntityID]
WHERE e.[BusinessEntityID] = @PersonID;

IF EXISTS(SELECT * FROM [Purchasing].[Vendor] AS v


INNER JOIN [Person].[BusinessEntityContact] bec
ON bec.[BusinessEntityID] = v.[BusinessEntityID]
WHERE bec.[PersonID] = @PersonID)
INSERT INTO @retContactInformation
SELECT @PersonID, p.FirstName, p.LastName, ct.[Name], 'Vendor Contact'
FROM [Purchasing].[Vendor] AS v
INNER JOIN [Person].[BusinessEntityContact] bec
ON bec.[BusinessEntityID] = v.[BusinessEntityID]
INNER JOIN [Person].ContactType ct
ON ct.[ContactTypeID] = bec.[ContactTypeID]
INNER JOIN [Person].[Person] p
ON p.[BusinessEntityID] = bec.[PersonID]
WHERE bec.[PersonID] = @PersonID;

IF EXISTS(SELECT * FROM [Sales].[Store] AS s


INNER JOIN [Person].[BusinessEntityContact] bec
ON bec.[BusinessEntityID] = s.[BusinessEntityID]
WHERE bec.[PersonID] = @PersonID)
INSERT INTO @retContactInformation
SELECT @PersonID, p.FirstName, p.LastName, ct.[Name], 'Store Contact'
FROM [Sales].[Store] AS s
INNER JOIN [Person].[BusinessEntityContact] bec
ON bec.[BusinessEntityID] = s.[BusinessEntityID]
INNER JOIN [Person].ContactType ct
ON ct.[ContactTypeID] = bec.[ContactTypeID]
INNER JOIN [Person].[Person] p
ON p.[BusinessEntityID] = bec.[PersonID]

DR. LUIS BOY CHAVIL Página 5


UNIVERSIDAD NACIONAL DE TRUJILLO Base de datos Avanzadas

WHERE bec.[PersonID] = @PersonID;


IF EXISTS(SELECT * FROM [Person].[Person] AS p
INNER JOIN [Sales].[Customer] AS c
ON c.[PersonID] = p.[BusinessEntityID]
WHERE p.[BusinessEntityID] = @PersonID AND c.[StoreID] IS NULL)
INSERT INTO @retContactInformation
SELECT @PersonID, p.FirstName, p.LastName, NULL, 'Consumer'
FROM [Person].[Person] AS p
INNER JOIN [Sales].[Customer] AS c
ON c.[PersonID] = p.[BusinessEntityID]
WHERE p.[BusinessEntityID] = @PersonID AND c.[StoreID] IS NULL;
END
RETURN;
END;
go

--Mostrar los datos de Información de contacto de IdPersona='5'


select *
from [dbo].[ufnGetContactInformation](5)

DR. LUIS BOY CHAVIL Página 6

También podría gustarte