Xavistian

SQL Procs, functions

Nov 8th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. /*1. Crear una función que devuelva el numero de empleados*/
  2. go
  3. CREATE FUNCTION fn_q_emp(/*parametros*/)
  4. returns int as
  5. begin
  6. /*Declarar variables (comienza con @)*/
  7. declare @qemp int
  8. /*Query*/
  9. select @qemp=Count(e.EmployeeID)
  10. from Employees e
  11. /*Retornar variable*/
  12. return @qemp
  13. end
  14. go
  15.  
  16. select dbo.fn_q_emp()
  17.  
  18.  
  19. /*2. Crear una función que devuelva el número de subordinados un jefe (Empleado)*/
  20. go
  21. CREATE FUNCTION fn_q_subj2(@jefeID int)
  22. returns int as
  23. begin
  24. declare @numemp int
  25. select @numemp=count(e.EmployeeID)
  26. from employees e join employees j on e.ReportsTo=j.EmployeeID
  27. where j.EmployeeID=@jefeID
  28. return @numemp
  29. end
  30. go
  31.  
  32. select dbo.fn_q_subj2(5) as Subordinados
  33.  
  34. /*3. Crear una función que liste el número de órdenes por empleado, si solo se conoce parte del nombre del empleado.*/
  35.  
  36. go
  37.  
  38. go
  39.  
  40. CREATE FUNCTION fn_OrdxEmpName(@firstletters nvarchar(10))
  41. returns TABLE as
  42. return
  43. (
  44. select e.EmployeeID, e.FirstName, COUNT(o.OrderID) as QOrdenes
  45. from Employees e join Orders o on e.EmployeeID=o.EmployeeID
  46. where e.FirstName LIKE @firstletters
  47. group by e.EmployeeID, e.FirstName
  48. )
  49.  
  50. select *
  51. from fn_OrdxEmpName('%A%A%')
  52.  
  53. /* 4. Crear una función que liste para un País (Parámetro de entrada), el Nombre de la compañía (CUSTOMERS),
  54. Ciudad (CUSTOMERS), País (CUSTOMERS), Nombre de Producto, Cantidad (QUANTITY), Precio Unitario y Descuento de Producto.*/
  55.  
  56.  
  57. CREATE FUNCTION fn_ordenes(@pais nvarchar(15))
  58. returns table as
  59. return
  60. (select c.CompanyName, c.City, c.Country, p.ProductName, od.Quantity, p.UnitPrice, od.Discount
  61. from Customers c join Orders o on o.CustomerID=c.CustomerID join [Order Details] od on od.OrderID=o.OrderID join Products p on p.ProductID=od.ProductID
  62. where c.Country like @pais)
  63.  
  64. select *
  65. from dbo.fn_ordenes('c%')
  66.  
  67.  
  68.  
  69. /*5. Ejecute la función Cos(0), luego la función Getdate( ) repetidas veces*/
  70.  
  71. select cos(0) --DETERMINISTICA
  72. select getdate() --NO DETERMINISTICA
  73.  
  74. /*6. Crear un procedimiento almacenado que liste el nombre de la compañía, nombre del contacto, ciudad y número de teléfono de los clientes*/
  75.  
  76. --PROCEDIMIENTO ALMACENADO=PROCEDIMIENTO=PROCEDURE=STORE PROCEDURE
  77. go
  78. create procedure sp_detalle_clientes /*parametro sin paréntesis*/
  79. as
  80. select c.CompanyName, c.ContactName, c.City, c.Phone
  81. from customers c
  82. go
  83.  
  84. exec sp_detalle_clientes
Advertisement
Add Comment
Please, Sign In to add comment