Advertisement
Teammasik

Laba_5_BD_triggers

Oct 21st, 2023 (edited)
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 2.23 KB | None | 0 0
  1. --task 1
  2. create or alter trigger CompanyDel
  3. on Company
  4. instead of delete
  5. as
  6. delete Department
  7. from deleted
  8. where deleted.Company_id = Department.Company_id
  9. delete Department_head
  10. from deleted
  11. join Department on Department.Company_id=deleted.Company_id
  12. join Department_head on Department_head.Dept_head_id = Department.Dept_head_id
  13. delete company from deleted
  14. where Company.Company_id = deleted.Company_id
  15.  
  16.  
  17. --task 2
  18. create or alter trigger UniqueWeek
  19. on Evaluation
  20. instead of insert
  21. as
  22. declare @Id int, @LDate date
  23. begin
  24. select @Id = inserted.Cooperator_id
  25. from inserted
  26. select @LDate = Evaluation.Date
  27. from Evaluation
  28. where Evaluation.Cooperator_id = @Id
  29.  
  30. if(select DATEDIFF(week, @Ldate, inserted.Date) from inserted) <> 0
  31.     insert into Evaluation
  32.     select inserted.Cooperator_id, inserted.Status, inserted.Date
  33.     from inserted
  34. else
  35.     print 'Не прошло недели'
  36. end
  37.  
  38. insert into Evaluation
  39. values('2',5,'15/10/2023')
  40.  
  41. --task 3
  42. create or alter trigger CooperCheck
  43. on Cooperator
  44. after insert
  45. as
  46. begin
  47.  DECLARE @DepID INT
  48.  DECLARE @CoopCount INT
  49.  
  50.  
  51.  SELECT @DepID = inserted.Dept_id from inserted
  52.  SELECT @CoopCount = Number_cooperator FROM Department_cooperator WHERE Department_cooperator.Dept_id = @DepID
  53.  
  54.   IF (@CoopCount > 4)
  55.  BEGIN
  56.   ROLLBACK TRANSACTION
  57.  END
  58.  ELSE
  59.  BEGIN
  60.   UPDATE Department_cooperator SET Number_cooperator = Number_cooperator + 1 WHERE Department_cooperator.Dept_id = @DepID
  61.  END
  62. END
  63.  
  64. insert into Cooperator
  65. values('Тестов','тест','15/10/2000','Уфа',100000,'Программист' ,'15/10/2023',2,'893422423','15465457')
  66.  
  67.  
  68. --zashita
  69. /*
  70. триггер который будет срабатывать при удалении департамента(отдела), если этот департамент последний то удаляем и компанию
  71. */
  72.  
  73. create trigger DeptDel
  74. on Department
  75. after delete
  76. as
  77. declare @Compid int
  78. begin
  79.     select @Compid = deleted.Company_id from deleted
  80.  
  81.     if not exists (select Department.Company_id from Department where Department.Company_id = @Compid)
  82.     begin
  83.         delete from Company where Company_id = @Compid
  84.     end
  85. end
  86.  
  87. delete from Department where Dept_id = 17
  88. delete from Department where Dept_id = 18
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement