Sie sind auf Seite 1von 5

UNIVERSIDAD NACIONAL DE TRUJILLO FACULTAD DE INGENIERA ESCUELA DE INGENIERA DE SISTEMAS LABORATORIO N 14 FUNCIONES DEFINIDAS POR EL USUARIO MG.

LUIS BOY CHAVIL EJERCICIOS DESARROLLADOS FUNCIONES ESCALARES -- Funcin para calcular un nmero elevado al cubo USE Northwind go if OBJECT_ID ('dbo.fnCubo', 'FN') is not null drop function fnCubo go create function dbo.fnCubo(@Numero float) returns float AS Begin return (@Numero * @Numero * @Numero) End go -- Ejecucin de la funcin fnCubo USE Northwind go select dbo.fnCubo(5) go -- Funciones Escalares con llamadas recursivas USE Northwind go if OBJECT_ID ('dbo.fnFactorial', 'FN') is not null drop function fnFactorial go create function dbo.fnFactorial(@Numero int) returns int AS Begin declare @n int if @Numero <= 1 SET @n = 1 ELSE SET @n = @Numero * dbo.fnFactorial(@Numero - 1) return (@n) End go

MG. LUIS BOY CHAVIL

Pgina 1

-- Ejecucin de la funcin fnFactorial USE Northwind go select dbo.fnFactorial(3) go

-- Funcin para calcular la cantidad agregada de un producto USE Northwind 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(UnitsInStock) from Products P where P.ProductID = @ProductID if (@ret is null) SET @ret = 0 return @ret End go -- Ejecucin de la funcin dbo.fnCanStockInventario para devolver la cantidad de inventario actual de aquellos productos que tienen un CategoryID entre 5 y 10 USE Northwind go select CategoryID, ProductName, dbo.fnCanStockInventario(ProductID) as 'Stock' from Products where CategoryID between 5 and 10; go FUNCIONES DE TABLA EN LNEA -- Funcin para obtener los agregados de las ventas hasta la fecha como YTD total para cada producto vendido en el almacen USE Northwind go if OBJECT_ID ('dbo.fnVentasporAlmacen', 'FN') is not null drop function dbo.fnVentasporAlmacen go create function dbo.fnVentasporAlmacen(@StoreID varchar(10)) returns table AS return ( select P.ProductID, P.ProductName, SUM(OD.UnitPrice * OD.Quantity) as 'YTD Total' from Products as P join [Order Details] as OD on OD.ProductID=P.ProductID MG. LUIS BOY CHAVIL Pgina 2

join Orders as O on O.OrderID = OD.OrderID where O.CustomerID = @StoreID group by P.ProductID, P.ProductName ) go -- Ejecutamos con ID del cliente 'ALFKI' USE Northwind go select * from dbo.fnVentasporAlmacen ('ALFKI') FUNCIONES DE TABLA DE MLTIPLES SENTENCIAS -- Cambio de la columna de una variable USE Northwind go if OBJECT_ID ('fnNombreEmpleados', 'FN') is not null drop function fnNombreEmpleados go create function fnNombreEmpleados(@formato nvarchar(9)) returns @TablaEmpleados TABLE (EmployeeID int primary key, FirstName nvarchar(100)) AS Begin if (@formato = 'SHORTNAME') INSERT @TablaEmpleados select EmployeeID, LastName from dbo.Employees else if (@formato = 'LONGNAME') INSERT @TablaEmpleados select EmployeeID, (Firstname+' '+Lastname)from dbo.Employees return END go -- Ahora, ejecutaremos la funcin de dos formas: -- Forma1: USE Northwind go select * from fnNombreEmpleados('LONGNAME') -- Forma2: USE Northwind go select * from fnNombreEmpleados('SHORTNAME')

MG. LUIS BOY CHAVIL

Pgina 3

USO DE FUNCIONES INTEGRADAS -- Uso de SUM USE Northwind go select ProductName, SUM(UnitPrice) from Products where Discontinued is not null and UnitsInStock != 0 and ProductName LIKE 'C%' group by ProductName order by ProductName; go

-- Uso de MAX USE Northwind go select MAX(Quantity) from [Order Details] go -- Uso de Min USE Northwind go select MIN(Quantity) from [Order Details] go

-- Uso de AVG USE Northwind go select AVG(UnitsOnOrder) as 'Promedio Unidades Ordenadas', SUM(UnitsInStock) as 'Suma unidades stock' from dbo.Products where ProductName LIKE 'C%' go -- Uso de Count USE Northwind go select COUNT(*), AVG(UnitsOnOrder) from Products where UnitPrice>10; go -- Uso de CAST USE Northwind go select SUBSTRING(ProductName, 1, 5) as ProductName, UnitPrice from Products where CAST(UnitPrice as Int) LIKE '3%' go MG. LUIS BOY CHAVIL Pgina 4

-- Usando CONVERT USE Northwind go select SUBSTRING(ProductName, 1, 5) as ProductName, UnitPrice from Products where CONVERT(Int,UnitPrice) LIKE '3%' go -- Concatenando expresiones no binarias que no son de caracteres mediante CAST USE Northwind go select 'La lista de precios es '+CAST(UnitPrice as varchar(12)) as ListaPrecio from Products where UnitPrice Between 35 and 40 go -- Uso de fechas fecha y hora actual del sistema select GETDATE() go -- Ao de la fecha actual select DATEPART("year", GETDATE()) go -- Nmero de das entre una fecha de la columna ModifiedDate y la fecha actual del sistema. select DATEDIFF("dd", BirthDate, GETDATE()) from Employees where EmployeeID=1 go -- Agregar 3 meses a la fecha actual select DATEADD("Month", 3, GETDATE()) go -- Mostrar todos los vendedores de cada departamento y el tiempo que tienen en la compaa USE Northwind go select Title, DATEDIFF("dd", Hiredate, GETDATE()) as Dias, DATEDIFF("week", Hiredate, GETDATE()) as Semanas, DATEDIFF("mm", Hiredate, GETDATE()) as Meses, DATEDIFF("yy", Hiredate, GETDATE()) as Aos from dbo.Employees where Title LIKE '%Sales%' go

MG. LUIS BOY CHAVIL

Pgina 5

Das könnte Ihnen auch gefallen