Xavistian

SQL triggers updated

Nov 15th, 2019
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.52 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
  85.  
  86. /* 7. Crear un procedimiento almacenado que actualice el precio unitario de los productos
  87. en un determinado porcentaje para una categoría. (Parámetros % = real, categoria = entero)*/
  88.  
  89. --1) Revisar el estado inicial
  90.  
  91. select *
  92. from Products o
  93. where o.CategoryID=2
  94.  
  95. /*
  96. 3 Aniseed Syrup 1 2 12 - 550 ml bottles 10.00 13 70 25 0
  97. 4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22.00 53 0 0 0
  98. */
  99.  
  100. --2) Realizar la transaccion
  101.  
  102. alter procedure sp_upd_price @per real, @cat int
  103. as
  104. begin transaction --SOLO PARA LAS TRANSACCIONES
  105. update Products
  106. set UnitPrice=UnitPrice+UnitPrice*(@per/100)
  107. where CategoryID=@cat
  108.  
  109. if @@ERROR!=0
  110. goto on_error
  111. else
  112. goto fin
  113.  
  114. on_error:
  115. rollback transaction
  116. fin:
  117. commit
  118.  
  119.  
  120. exec sp_upd_price 10,1
  121.  
  122. --1 Chai 1 1 10 boxes x 20 bags 18.00 39 0 10 0
  123. --2 Chang 1 1 24 - 12 oz bottles 19.00 17 40 25 0
  124. --3)Comprobar la ejecucion
  125.  
  126. select *
  127. from Products
  128. where CategoryID=1
  129.  
  130.  
  131. /* 9. Crear un trigger que notifique en una tabla eventos(fecha, motivo), si las unidades en stock de la(s) tupla(s) de tabla PRODUCTS es menor a 5.
  132. En la entidad eventos, fecha de tipo “DATETIME” y motivo de tipo Varchar(255) */
  133.  
  134. create table Eventos
  135. (Fecha datetime, Motivo varchar(255))
  136.  
  137. select *
  138. from Eventos
  139.  
  140. create trigger tr_productos
  141. --1)Donde y cuando se dispara el trigger
  142. --tabla y transaccion
  143. on products
  144. for update
  145. as
  146. begin
  147. --2)Que debe hacer el trigger
  148. if update(UnitsInStock)
  149. begin
  150. insert into Eventos
  151. select getdate() 'Fecha','Limite de stock del producto '+ rtrim(ltrim(str(p.ProductID))) 'Limite de stock'
  152. from inserted p /*inserted o deleted*/
  153. where p.UnitsInStock<=5
  154. end
  155. end
  156.  
  157. --1 Revisar estado inicial
  158. select *
  159. from Products
  160.  
  161. select *
  162. from Eventos
  163. -- <<<<<<<<<<<<<<<<<<<<<<<<<<<<<1 Chai 1 1 10 boxes x 20 bags 19.406 39 0 10 0
  164. --2 Ejecutar la transaccion
  165. update Products
  166. set UnitsInStock=3
  167. where ProductID=1
  168.  
  169. update Products
  170. set ProductName='Chai'
  171. where ProductID=1
  172. --3 Revisar la ejecución
  173. select *
  174. from Eventos
  175.  
  176. delete
  177. from Eventos
  178. where
  179. /*while (@@ERROR=0)
  180. insert into Eventos
  181. select getdate() 'Fecha','Limite de stock del producto '+ rtrim(ltrim(str(p.ProductID))) 'Limite de stock'
  182. from Products p
  183. where p.UnitsInStock<=5*/
  184.  
  185.  
  186.  
  187. /*10. Sean las dos tablas siguientes:
  188. /*Tabla Departamento
  189. CDepartamento int PK,
  190. NDepartamento varchar(255),
  191. NLocalidad varchar(255),
  192. QEmpleados int */
  193. /* EMPLEADO
  194. CEmpleado int PK,
  195. NEmpleado varchar(255),
  196. CDepartamento int FK */
  197. a) Crear un trigger que sume +1 el QEmpleados de un departamento cada vez que se inserte un empleado
  198. b) Crear un trigger que reste -1 el QEmpleados de un departamento cada vez que se eliimne un empleado
  199. */
  200.  
  201. go
  202. create table Departamento
  203. (
  204. CDepartamento int NOT NULL,
  205. NDepartamento varchar(255),
  206. NLocalidad varchar (255),
  207. QEmpleados int,
  208. PRIMARY KEY(CDepartamento)
  209. )
  210.  
  211. create table Empleado
  212. (
  213. CEmpleado int NOT NULL,
  214. NEmpleado varchar(255),
  215. CDepartamento int,
  216. PRIMARY KEY (CEmpleado),
  217. FOREIGN KEY (CDepartamento)REFERENCES Departamento (CDepartamento)
  218. )
  219.  
  220. create trigger sum_Employees
  221. on Empleado
  222. for insert
  223. as
  224. begin
  225. update Departamento
  226. set QEmpleados=QEmpleados+1
  227. from inserted
  228. where inserted.CDepartamento=Departamento.CDepartamento
  229. end
  230. go
  231.  
  232. create trigger del_Employees
  233. on Empleado
  234. for delete
  235. as
  236. begin
  237. update Departamento
  238. set QEmpleados=QEmpleados-1
  239. from deleted
  240. where deleted.CDepartamento=Departamento.CDepartamento
  241. end
  242. go
  243.  
  244. select *
  245. from Empleado
  246.  
  247. insert into Departamento values (3,'Chiclayo', 'Pimentel', 0), (2,'Lima','Miraflores',2)
  248.  
  249. insert into Empleado values (1,'Ricardo', 1)
  250. select *
  251. from Empleado
  252. select *
  253. from Departamento
  254.  
  255. delete from Empleado where Empleado.NEmpleado='Ricardo'
  256. /*
  257.  
  258. create trigger tr_productos
  259. --1)Donde y cuando se dispara el trigger
  260. --tabla y transaccion
  261. on products
  262. for update
  263. as
  264. begin
  265. --2)Que debe hacer el trigger
  266. if update(UnitsInStock)
  267. begin
  268. insert into Eventos
  269. select getdate() 'Fecha','Limite de stock del producto '+ rtrim(ltrim(str(p.ProductID))) 'Limite de stock'
  270. from inserted p /*inserted o deleted*/
  271. where p.UnitsInStock<=5
  272. end
  273. end*/
Advertisement
Add Comment
Please, Sign In to add comment