Advertisement
didito33

3rd one

May 14th, 2022
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.09 KB | None | 0 0
  1. use school_sport_clubs;
  2. drop procedure testProc;
  3.  
  4. delimiter $$
  5. CREATE PROCEDURE testProc(IN param int)
  6. out_block:
  7. BEGIN
  8. DECLARE res int;
  9. SET res = param;
  10. inner_block:
  11. BEGIN
  12. IF (res = 1)
  13. THEN
  14. LEAVE inner_block;
  15. END IF;
  16. SELECT 'This will be excuted only if param is 0';
  17. END inner_block;
  18. SELECT 'End of program';
  19. END out_block;
  20. $$
  21. delimiter ;
  22.  
  23. call testProc(1);
  24.  
  25. select now();
  26. select month(now());
  27. select year(now());
  28.  
  29. use school_sport_clubs;
  30. drop procedure if exists monthSalaryPayment;
  31. delimiter |
  32. create procedure monthSalaryPayment(IN monthOfPayment INT, in yearOFpayment INT, OUT success bit)
  33. procLab: begin
  34. declare tempCoachSalary decimal;
  35. declare currentcoachSalary decimal;
  36. declare iterator int;
  37. declare countOfCoaches int;
  38. declare tempCoachId int;
  39. declare updatedSalaryCounter int;
  40. declare countOfCoachesWithoutMonthSalary int;
  41. DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'SQLException occured';
  42.  
  43. create temporary table tempCoach(
  44. id int auto_increment primary key,
  45. coach_id int not null,
  46. month_salary int not null
  47. )Engine = Memory;
  48.  
  49. INSERT INTO tempCoach(coach_id,month_salary)
  50. SELECT coaches.id, coaches.month_salary
  51. FROM coaches
  52. WHERE month_salary IS NOT NULL ;
  53.  
  54. SELECT COUNT(*)
  55. INTO countOfCoaches
  56. FROM tempCoach;
  57.  
  58. SET countOfCoachesWithoutMonthSalary = 0;
  59. set iterator = 1;
  60. WHILE(iterator >= 1 AND iterator <= countOfCoaches) # преброяваме колко са треньорите, които не са си полчуили заплатата все още.
  61. DO
  62. SELECT coach_id, month_salary
  63. INTO tempCoachId, tempCoachSalary
  64. FROM tempCoach
  65. where id = iterator;
  66.  
  67. SELECT salaryAmount
  68. INTO currentCoachSalary #има ли заплата вече преведена за този месец и тази година този треньор
  69. FROM salarypayments
  70. WHERE `month` = monthOfPayment
  71. AND `year` = yearOFpayment
  72. AND `coach_id` = tempCoachId;
  73.  
  74. IF(IFNULL(currentCoachSalary,0) <= tempCoachSalary)
  75. THEN
  76. SET countOfCoachesWithoutMonthSalary = countOfCoachesWithoutMonthSalary +1;
  77. END IF;
  78. SET iterator = iterator +1;
  79. end while;
  80. IF(countOfCoachesWithoutMonthSalary = 0) # ако няма треньори, които си чакат превод на заплатата
  81. THEN
  82. drop table tempCoach;
  83. set success = 0;
  84. LEAVE procLab;
  85. ELSE set iterator = 1;
  86. SET updatedSalaryCounter = 0;
  87. START TRANSACTION;
  88. WHILE(iterator >= 1 AND iterator <= countOfCoaches)
  89. DO
  90. SELECT coach_id, month_salary
  91. INTO tempCoachId, tempCoachSalary
  92. FROM tempCoach
  93. where id = iterator;
  94.  
  95. SELECT salaryAmount
  96. INTO currentCoachSalary #има ли заплата вече преведена за този месец и тази година този треньор
  97. FROM salarypayments
  98. WHERE `month` = monthOfPayment
  99. AND `year` = yearOFpayment
  100. AND `coach_id` = tempCoachId;
  101.  
  102.  
  103. IF(IFNULL(currentCoachSalary,0) < tempCoachSalary)
  104. THEN
  105. INSERT INTO salarypayments(`coach_id`,`month`,`year`,`salaryAmount`,`dateOfPayment`)
  106. VALUES (tempCoachId, monthOfPayment,yearOFpayment, tempCoachSalary, NOW())
  107. ON duplicate key update #ако вече хонорарите му са преведени, то към тези пари да се добави и месечната му заплата.
  108. salaryAmount = salaryAmount + tempCoachSalary,
  109. dateOfPayment = NOW();
  110. set updatedSalaryCounter = updatedSalaryCounter + 1;
  111. ELSE
  112. SELECT 'The coach has a month salary yet!';
  113. END IF;
  114. SET iterator = iterator +1;
  115. end while;
  116. IF(countOfCoachesWithoutMonthSalary = updatedSalaryCounter) # преведени са толкова заплати, колкото е трябвало
  117. THEN
  118. commit;
  119. SET success = 1;
  120. drop table tempCoach;
  121. ELSE
  122. rollback;
  123. SET success = 0;
  124. drop table tempCoach;
  125. END if;
  126. END IF;
  127. end
  128. |
  129. DELIMITER ;
  130.  
  131. -- proc 2
  132. use school_sport_clubs;
  133.  
  134. drop procedure if exists monthHonorariumPayment;
  135.  
  136. delimiter |
  137. create procedure monthHonorariumPayment(IN monthOfPayment INT, in yearOFpayment INT)
  138. procLabel: begin
  139. declare countOfCoaches int;
  140. declare iterator int;
  141. declare countOfRowsBeforeUpdate int;
  142. declare countOfRowsAfterUpdate int;
  143. DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'SQLException occured';
  144.  
  145.  
  146. create temporary table tempCoaches(
  147. id int auto_increment primary key,
  148. coach_id int not null,
  149. monthHourSum int
  150. )Engine = Memory;
  151.  
  152.  
  153. create temporary table tempTbl(
  154. id int auto_increment primary key,
  155. coach_id int,
  156. number_of_hours int,
  157. pay_for_hour decimal,
  158. amount decimal,
  159. paymentMonth int,
  160. paymentYear int
  161. )Engine = Memory;
  162.  
  163. #Плащане на редовна месечна заплата:
  164. SET @RESULT =0;
  165. SELECt @RESULT;
  166. call monthSalaryPayment(monthOfPayment,yearOFpayment,@RESULT);
  167.  
  168. SELECT COUNT(*)
  169. INTO countOfRowsBeforeUpdate
  170. FROM coach_work
  171. where month(coach_work.date) = monthOfPayment
  172. AND YEAR(coach_work.date) = yearOFpayment
  173. AND isPayed = 0;
  174.  
  175. INSERT INTO tempCoaches(coach_id, monthHourSum) #записваме всички треньори и сумата от техните часове в табличка за дадения месец на дадената година
  176. SELECT coach_id, SUM(number_of_hours)
  177. FROM coach_work
  178. where month(coach_work.date) = monthOfPayment
  179. AND YEAR(coach_work.date) = yearOFpayment
  180. AND isPayed = 0
  181. GROUP BY coach_work.coach_id;
  182.  
  183. set iterator = 1;
  184. SELECT COUNT(*)
  185. INTO countOfCoaches
  186. FROM tempCoaches;
  187.  
  188. IF(ifnull(countOfCoaches,0) = 0) #Няма треньори, за които да се извършва плащане
  189. THEN SELECT 'No coaches and hours for this payment period';
  190. drop table tempTbl;
  191. drop table tempCoaches;
  192. LEAVE procLabel;
  193. ELSE
  194. START TRANSACTION;
  195. WHILE(iterator >= 1 AND iterator <= countOfCoaches)
  196. DO
  197. INSERT INTO tempTbl(coach_id, number_of_hours, pay_for_hour, amount, paymentMonth,paymentYear)
  198. SELECT tc.coach_id, tc.monthHourSum, c.hour_salary, tc.monthHourSum*c.hour_salary, monthOfPayment, yearOFpayment
  199. FROM tempCoaches as tc JOIN coaches as c
  200. ON tc.coach_id = c.id
  201. WHERE tc.id = iterator;
  202. SET iterator = iterator + 1;
  203.  
  204. END WHILE;
  205.  
  206. INSERT INTO salarypayments(`coach_id`, `month`,`year`,`salaryAmount`,`dateOfPayment`)
  207. SELECT coach_id, paymentMonth, paymentYear, amount, NOW()
  208. FROM tempTbl
  209. ON DUPLICATE KEY UPDATE
  210. salaryAmount = salaryAmount + amount,
  211. dateOfPayment = NOW();
  212.  
  213.  
  214. UPDATE coach_work
  215. SET isPayed = 1
  216. WHERE month(coach_work.date) = monthOfPayment
  217. AND YEAR(coach_work.date) = yearOFpayment
  218. AND isPayed = 0;
  219.  
  220. SELECT ROW_COUNT() INTO countOfRowsAfterUpdate;
  221.  
  222. IF(countOfRowsBeforeUpdate = countOfRowsAfterUpdate)
  223. THEN
  224. commit;
  225. ELSE
  226. rollback;
  227. END IF;
  228.  
  229. drop table tempTbl;
  230. drop table tempCoaches;
  231. END IF;
  232. END
  233. |
  234. DELIMITER ;
  235.  
  236. call monthHonorariumPayment(3, 2022);
  237.  
  238.  
  239. -- курсори
  240. use school_sport_clubs;
  241. drop procedure if exists CursorTest;
  242. delimiter |
  243. create procedure CursorTest()
  244. begin
  245. declare finished int;
  246. declare tempName varchar(100);
  247. declare tempEgn varchar(10);
  248. declare coachCursor CURSOR for
  249. SELECT name, egn
  250. from coaches
  251. where month_salary is not null;
  252. declare continue handler FOR NOT FOUND set finished = 1;
  253. set finished = 0;
  254. OPEN coachCursor;
  255. coach_loop: while( finished = 0)
  256. DO
  257. FETCH coachCursor INTO tempName,tempEgn;
  258. IF(finished = 1)
  259. THEN
  260. LEAVE coach_loop;
  261. END IF;
  262. SELECT tempName,tempEgn; # or do something with these variables...
  263. end while;
  264. CLOSE coachCursor;
  265. SET finished = 0;
  266. SELECT 'Finished!';
  267. end;
  268. |
  269. delimiter |
  270.  
  271. -- TRIGGERS
  272. delimiter |
  273. CREATE TRIGGER after_salarypayment_update AFTER UPDATE ON salarypayments
  274. FOR EACH ROW
  275. BEGIN
  276. INSERT INTO salarypayments_log(operation,
  277. old_coach_id,
  278. new_coach_id,
  279. old_month,
  280. new_month,
  281. old_year,
  282. new_year,
  283. old_salaryAmount,
  284. new_salaryAmount,
  285. old_dateOfPayment,
  286. new_dateOfPayment,
  287. dateOfLog)
  288. VALUES ('UPDATE',OLD.coach_id,NEW.coach_id,OLD.month,NEW.month,
  289. OLD.year,NEW.year,OLD.salaryAmount,NEW.salaryAmount,OLD.dateOfPayment,NEW.dateOfPayment,NOW());
  290. END;
  291. |
  292. Delimiter ;
  293. select * from salarypayments;
  294. select * from salarypayments_log;
  295.  
  296. UPDATE `salarypayments` SET `salaryAmount`='2000' WHERE `id`='13';
  297.  
  298.  
  299. -- 1. Създайте VIEW, с което извеждате информация за името на треньора, името
  300. -- на спорта, чийто тренировки води, информация за група, която тренира,
  301. -- както и сумата, която е получил за текущия месец. Резултатната таблица
  302. -- трябва да изглежда така:
  303. drop view if exists coachinfo;
  304.  
  305. CREATE VIEW coachinfo(name, groupInfo, sport, year, month, salaryAmaounth) as
  306. SELECT coaches.name, concat(sportgroups.id, ' - ', sportgroups.location), sports.name, year(now()), month(now()), salarypayments.salaryAmount
  307. FROM coaches
  308. JOIN sportgroups
  309. ON coaches.id = sportgroups.coach_id
  310. JOIN sports
  311. ON sports.id = sportgroups.sport_id
  312. JOIN salarypayments
  313. ON coaches.id = salarypayments.coach_id
  314. WHERE salarypayments.year = year(now())
  315. AND salarypayments.month = month(now());
  316.  
  317. select * from coachinfo;
  318.  
  319. -- 2. Създайте тригер, който при изтриване на информация от таблицата
  320. -- salarypayments записва изтритата информация в таблицата
  321. -- salarypayments_log.
  322.  
  323. delimiter |
  324. CREATE TRIGGER after_salarypayment_delete BEFORE DELETE ON salarypayments
  325. FOR EACH ROW BEGIN
  326. INSERT INTO salarypayments_log(operation,
  327. old_coach_id,
  328. new_coach_id,
  329. old_month,
  330. new_month,
  331. old_year,
  332. new_year,
  333. old_salaryAmount,
  334. new_salaryAmount,
  335. old_dateOfPayment,
  336. new_dateOfPayment,
  337. dateOfLog)
  338. VALUES ('DELETE',OLD.coach_id,null,OLD.month,null,
  339. OLD.year,null,OLD.salaryAmount,null,OLD.dateOfPayment,null,NOW());
  340. END |
  341. Delimiter ;
  342.  
  343.  
  344. -- 3. Изтрийте цялата информация от таблицата salarypayments и напишете
  345. -- заявка, с която я възстановявате.
  346. INSERT INTO salarypayments (coach_id, month, year, salaryAmount, dateOfPayment)
  347. select DISTINCT old_coach_id, old_month, old_year, old_salaryAmount, old_dateOfPayment
  348. FROM salarypayments_log
  349. WHERE operation LIKE 'DELETE';
  350.  
  351.  
  352. -- 4. Използвайте базата данни transaction_test. Създайте процедура, която
  353. -- конвертира суми от лева в евро и обратно по курса на БНБ. за прехвърляне
  354. -- на пари от една сметка в друга.
  355.  
  356. DELIMITER $
  357.  
  358. CREATE PROCEDURE changeMoney(INOUT amount_of_money DOUBLE, IN course_out VARCHAR(50),IN course_in VARCHAR(50))
  359. BEGIN
  360. IF(course_out = 'BGN' && course_in='EUR') THEN SET amount_of_money = amount_of_money*0.51;
  361. ELSEIF(course_out = 'EUR' && course_in='BGN') THEN SET amount_of_money = amount_of_money*1.96;
  362. ELSEIF(course_out = 'BGN' && course_in='BGN') THEN SET amount_of_money = amount_of_money;
  363. ELSEIF(course_out = 'EUR' && course_in='EUR') THEN SET amount_of_money = amount_of_money;
  364. END IF;
  365. END $
  366.  
  367. DELIMITER ;
  368. DROP PROCEDURE changeMoney;
  369.  
  370. SET @amount_of_money = 5 ;
  371. CALL changeMoney(@amount_of_money,'EUR','BGN');
  372. SELECT @amount_of_money;
  373.  
  374.  
  375. -- 5. Създайте процедура за прехвърляне на пари от една сметка в друга. Нека
  376. -- процедурата да извежда съобщение за грешка ако няма достатъчно пари, за
  377. -- да се осъществи успешно трансакцията или ако трансакцията е неуспешна.
  378. -- Направете проверка за вида на валутите, в които са сметките – ако са в лева
  379. -- или евро – извикайте процедурата от предишната задача, в противен случай
  380. -- изведете съобщение за грешка и прекратете процедурата. Нека тя да
  381. -- получава като параметри ID на сметката от която се прехвърля, ID на
  382. -- сметката на получателя и сумата, която трябва да се преведе.
  383.  
  384. DELIMITER $$
  385. CREATE PROCEDURE transfer_money_in_anotherAcc(customer_OUT INT, customer_IN INT, amount_to_add DOUBLE)
  386. BEGIN
  387. START TRANSACTION;
  388. IF((SELECT ca.amount FROM customer_accounts AS ca WHERE ca.id = customer_OUT) < amount_to_add OR amount_to_add<0) THEN ROLLBACK;
  389.  
  390. ELSEIF((SELECT currency FROM customer_accounts WHERE id=customer_OUT) NOT IN('BGN','EUR')) THEN ROLLBACK;
  391.  
  392. ELSEIF((SELECT currency FROM customer_accounts WHERE id=customer_IN) NOT IN('BGN','EUR')) THEN ROLLBACK;
  393.  
  394. ELSE
  395. UPDATE customer_accounts
  396. SET amount = amount - amount_to_add
  397. WHERE customer_accounts.id = customer_OUT;
  398. IF (ROW_COUNT() != 1) THEN ROLLBACK;
  399.  
  400. ELSE
  401. CALL changeMoney(amount_to_add,(SELECT currency FROM customer_accounts WHERE id=customer_OUT),
  402. (SELECT currency FROM customer_accounts WHERE id=customer_IN));
  403. UPDATE customer_accounts
  404. SET amount = amount + amount_to_add
  405. WHERE customer_accounts.id = customer_IN;
  406. IF (ROW_COUNT() != 1) THEN ROLLBACK;
  407. END IF;
  408. END IF;
  409. END IF;
  410. IF (ROW_COUNT() != 1) THEN SELECT 'FAIL';
  411. END IF;
  412. COMMIT;
  413. END $$
  414. DELIMITER ;
  415.  
  416. DROP PROCEDURE transfer_money_in_anotherAcc;
  417. SET @amount_of_money = 6.11;
  418. CALL transfer_money_in_anotherAcc(1,2,@amount_of_money);
  419. select * from customer_accounts;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement