You are on page 1of 5

FUNCIONES ESCALARES -- Funcin para calcular un nmero elevado al cubo USE AdventureWorks 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 AdventureWorks go select dbo.fnCubo(5) go -- Funciones Escalares con llamadas recursivas USE AdventureWorks 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

Pgina 1

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

-- Funcin para calcular la cantidad agregada de un producto USE AdventureWorks 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 -- Ejecucin de la funcin dbo.fnCanStockInventario para devolver -- la cantidad de inventario actual de aquellos productos que tienen -- un ProductModelID entre 75 y 80 USE AdventureWorks go select ProductModelID, Name, dbo.fnCanStockInventario(productID) from Production.Product where ProductModelID between 75 and 80; 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 AdventureWorks 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 'YTD Total' Pgina 2

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 '10' USE AdventureWorks go select * from sales.fnVentasporAlmacen (10)

FUNCIONES DE TABLA DE MLTIPLES SENTENCIAS


-- Cambio de la columna de una variable USE AdventureWorks go if OBJECT_ID ('HumanResources.fnNombreEmpleados', 'FN') is not null drop function HumanResources.fnNombreEmpleados go create function HumanResources.fnNombreEmpleados(@formato nvarchar(9)) returns @TablaEmpleados TABLE (EmployeeID int primary key, [Employee Name] nvarchar(100)) AS Begin if (@formato = 'SHORTNAME') INSERT @TablaEmpleados select EmployeeID, LastName from HumanResources.vEmployee else if (@formato = 'LONGNAME') INSERT @TablaEmpleados select EmployeeID, (Firstname+' '+Lastname) from HumanResources.vEmployee return END go -- Ahora, ejecutaremos la funcin de dos formas: -- Forma1: USE AdventureWorks go select * from HumanResources.fnNombreEmpleados('LONGNAME') -- Forma2: USE AdventureWorks go select * from HumanResources.fnNombreEmpleados('SHORTNAME')

Pgina 3

USO DE FUNCIONES INTEGRADAS


-- Uso de SUM USE AdventureWorks go select Color, SUM(ListPrice), SUM(StandardCost) from Production.Product where Color is not null and ListPrice != 0.00 and Name LIKE 'Mountain%' group by Color order by Color; go

-- Uso de MAX USE AdventureWorks go select MAX(TaxRate) from Sales.SalesTaxRate go -- Uso de Min USE AdventureWorks go select MIN(TaxRate) from Sales.SalesTaxRate go

-- Uso de AVG USE AdventureWorks go select AVG(VacationHours) as 'Promedio de horas de vacaciones', SUM(SickleaveHours) as 'Total de Sick Hours' from HumanResources.Employee where Title LIKE 'Vice President%' go -- Uso de Count USE AdventureWorks go select COUNT(*), AVG(Bonus) from Sales.SalesPerson where SalesQuota>25000; go -- Uso de CAST USE AdventureWorks go select SUBSTRING(Name, 1, 30) as ProductName, listPrice from Production.Product where CAST(ListPrice as Int) LIKE '3%' go Pgina 4

-- Usando CONVERT USE AdventureWorks go select SUBSTRING(Name, 1, 30) as ProductName, listPrice from Production.Product where CONVERT(int, ListPrice) LIKE '3%' go -- Concatenando expresiones no binarias que no son de -- caracteres mediante CAST USE AdventureWorks go select 'La lista de precios es '+CAST(ListPrice as varchar(12)) as ListaPrecio from Production.Product where ListPrice Between 350.00 and 400.00 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", ModifiedDate, GETDATE()) from HumanResources.Employee where EmployeeID=1 go -- Agregar 3 meses a la fecha actual select DATEADD("Month", 3, GETDATE()) go -- Mostrar todos los vicepresidentes de cada departamento -- y el tiempo que tienen en la compaa USE AdventureWorks 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 HumanResources.Employee where Title LIKE '%Vice%' go

Pgina 5

You might also like