-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDAY_4.sql
More file actions
1364 lines (980 loc) · 28.6 KB
/
DAY_4.sql
File metadata and controls
1364 lines (980 loc) · 28.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## MySQL constraints --------------
/*
1. NOT NULL constraint
2. Primary Key
3. Foreign key
4. UNIQUE constraint
5. CHECK Constraint
*/
# Not Null
CREATE TABLE tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
start_date DATE NOT NULL,
end_date DATE
);
INSERT INTO tasks(title ,start_date, end_date)
VALUES('Learn MySQL NOT NULL constraint', '2017-02-01','2017-02-02'),
('Check and update NOT NULL consttasksraint to your database', '2017-02-01',NULL);
SELECT *
FROM tasks
WHERE end_date IS NULL;
UPDATE tasks
SET
end_date = start_date + 7
WHERE
end_date IS NULL;
SELECT * FROM tasks;
ALTER TABLE tasks
CHANGE
end_date
end_date DATE NOT NULL;
DESCRIBE tasks;
# primary key
CREATE TABLE users(
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40),
password VARCHAR(255),
email VARCHAR(255)
);
CREATE TABLE pkdemos(
id INT,
title VARCHAR(255) NOT NULL
);
DESCRIBE pkdemos;
ALTER TABLE pkdemos
ADD PRIMARY KEY(id);
## Foreign key
/*
MySQL has five reference options: CASCADE, SET NULL, NO ACTION, RESTRICT, and SET DEFAULT.
CASCADE: if a row from the parent table is deleted or updated, the values of the matching
rows in the child table automatically deleted or updated.
SET NULL: if a row from the parent table is deleted or updated, the values of the
foreign key column (or columns) in the child table are set to NULL.
RESTRICT: if a row from the parent table has a matching row in the child table,
MySQL rejects deleting or updating rows in the parent table.
NO ACTION: is the same as RESTRICT.
SET DEFAULT: is recognized by the MySQL parser. However, this action is rejected by
both InnoDB and NDB tables.
*/
CREATE DATABASE fkdemo;
USE fkdemo;
CREATE TABLE categories(
categoryId INT AUTO_INCREMENT PRIMARY KEY,
categoryName VARCHAR(100) NOT NULL
) ;
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
) ENGINE=INNODB;
INSERT INTO categories(categoryName)
VALUES
('Smartphone'),
('Smartwatch');
INSERT INTO products(productName, categoryId)
VALUES('iPhone',1);
select * from categories;
select * from products;
# Attempt to insert a new row into the products table with a categoryId
# value does not exist in the categories table
INSERT INTO products(productName, categoryId)
VALUES('iPad',3);
# Update the value in the categoryId column in the categories table to 100
UPDATE categories
SET categoryId = 100
WHERE categoryId = 1;
# Note: Because of the RESTRICT option, you cannot delete or
# update categoryId 1 since it is referenced by the productId 1 in the products table.
DROP TABLE products;
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT NOT NULL,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=INNODB;
## Unique Constraint
CREATE TABLE suppliers (
supplier_id INT AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
phone VARCHAR(15) NOT NULL UNIQUE,
address VARCHAR(255) NOT NULL,
PRIMARY KEY (supplier_id),
CONSTRAINT uc_name_address UNIQUE (name , address)
);
INSERT INTO suppliers(name, phone, address)
VALUES( 'ABC Inc1',
'(408)-908-24761',
'4000 North 1st Street1');
# insert a different supplier but has the
# phone number that already exists in the suppliers table
select * from suppliers;
INSERT INTO suppliers(name, phone, address)
VALUES( 'XYZ Corporation','(408)-908-2476','3000 North 1st Street');
# change the phone number to a different one and execute the insert statement again
INSERT INTO suppliers(name, phone, address)
VALUES( 'XYZ Corporation','(408)-908-3333','3000 North 1st Street');
## CHECK CONSTRAINT
CREATE TABLE parts (
part_no VARCHAR(18) PRIMARY KEY,
description VARCHAR(40),
cost DECIMAL(10,2 ) NOT NULL CHECK (cost >= 0),
price DECIMAL(10,2) NOT NULL CHECK (price >= 0),
age int Not null check (age >=0 and age<=100)
);
INSERT INTO parts(part_no, description,cost,price, age)
VALUES('A-001','Cooler',0,100, 350);
# new clause defines a table CHECK
# constraint that ensures the price is always greater than or equal to cost
CREATE TABLE parts (
part_no VARCHAR(18) PRIMARY KEY,
description VARCHAR(40),
cost DECIMAL(10,2 ) NOT NULL CHECK (cost >= 0),
price DECIMAL(10,2) NOT NULL CHECK (price >= 0),
CONSTRAINT parts_chk_price_gt_cost
CHECK(price >= cost)
);
INSERT INTO parts(part_no, description,cost,price)
VALUES('A-001','Cooler',200,100);
## STORED PROCEDURE -----------------------------------------------------
/*
If you want to save this query on the database server for execution later,
one way to do it is to use a stored procedure.
By definition, a stored procedure is a segment of declarative SQL statements
stored inside the MySQL Server.
Advantages:
1. Reduce network traffic
2. Centralize business logic in the database
3. Make database more secure
Disadvantages :
1. Resource usages
2. Troubleshooting
3. Maintenances
# General Syntax
DELIMITER $$
CREATE PROCEDURE sp_name()
BEGIN
-- statements
END $$
DELIMITER ;
*/
# SELECT statement returns all rows in the table customers from the sample database
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
# CREATE PROCEDURE statement creates a new stored procedure that wraps the query above
DELIMITER $$
CREATE PROCEDURE stp_GetCustomers()
BEGIN
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
END$$
DELIMITER ;
# invoke it by using the CALL statement
CALL stp_GetCustomers(idd, time);
# 1 . create a new stored procedure that returns employee and office information for one user:
DELIMITER $$
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT
firstName,
lastName,
city,
state,
country
FROM employees
INNER JOIN offices using (officeCode);
END$$
DELIMITER ;
# 2. Call procedure
CALL GetEmployees();
# 3. DROP PROCEDURE to delete the GetEmployees() stored procedure:
DROP PROCEDURE GetEmployees;
DROP PROCEDURE IF EXISTS GetEmployees;
# Stored Procedure Variables ----------------------------
/*
variables in stored procedures to hold immediate results.
These variables are local to the stored procedure.
Syntax:
DECLARE variable_name datatype(size) [DEFAULT default_value];
*/
# declares a variable named totalSale with the data type DEC(10,2) and default value 0.0
# DECLARE totalSale DEC(10,2) DEFAULT 0.0;
# DECLARE x, y INT DEFAULT 0;
# Once a variable is declared, it is ready to use. To assign a variable a value,
# you use the SET statement
SET variable_name = value;
# EG.
# DECLARE total INT DEFAULT 0;
SET @total2 = 10;
select @total2
DELIMITER $$
CREATE PROCEDURE GetTotalOrder()
BEGIN
DECLARE totalOrder INT DEFAULT 0;
SELECT COUNT(*)
INTO totalOrder
FROM orders;
SELECT totalOrder;
END$$
DELIMITER ;
CALL GetTotalOrder();
SELECT COUNT(*)
FROM orders;
# stored procedure parameters ------------------------
/*
A parameter in a stored procedure has one of three modes: IN,OUT, or INOUT.
1. IN : is the default mode. When you define an IN parameter in a stored procedure,
the calling program has to pass an argument to the stored procedure.
2. OUT : The value of an OUT parameter can be changed inside the stored procedure
and its new value is passed back to the calling program.
3. INOUT : An INOUT parameter is a combination of IN and OUT parameters.
It means that the calling program may pass the argument, and the stored
procedure can modify the INOUT parameter, and pass the new value back to the calling program.
syntax of defining a parameter in stored procedures:
[IN | OUT | INOUT] parameter_name datatype[(length)]
*/
# 1. creates a stored procedure that finds all offices
# that locate in a country specified by the input parameter
SELECT *
FROM offices
WHERE country = "USA";
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(
IN countryName VARCHAR(255)
)
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //
DELIMITER ;
CALL GetOfficeByCountry();
CALL GetOfficeByCountry('USA');
CALL GetOfficeByCountry('France')
# 2. returns the number of orders by order status
DELIMITER $$
CREATE PROCEDURE GetOrderCountByStatus (
IN orderStatus VARCHAR(25),
OUT total INT
)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$
DELIMITER ;
CALL GetOrderCountByStatus('Shipped', @total);
SELECT @total; # Session Variables
# 3. INOUT STP
DELIMITER $$
CREATE PROCEDURE SetCounter(
INOUT counter INT,
IN inc INT
)
BEGIN
SET counter = counter + inc;
END$$
DELIMITER ;
SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8
# Alter Stored Procedures --------------
/*
Sometimes, you may want to alter a stored procedure by adding or
removing parameters or even changing its body.
Fortunately, MySQL does not have any statement that allows you to
directly modify the parameters and body of the stored procedure.
To make such changes, you must drop ad re-create the
stored procedure using the DROP PROCEDURE and
CREATE PROCEDURE statements.
*/
# 1. create a stored procedure that returns the total amount of all sales orders
DELIMITER $$
CREATE PROCEDURE GetOrderAmount()
BEGIN
SELECT
SUM(quantityOrdered * priceEach)
FROM orderDetails;
END$$
DELIMITER ;
# Alter STP by get the total amount by a given sales order
# Note: Second, right-click the stored procedure that you want
# to change and select Alter Stored Procedure…
DELIMITER $$
CREATE PROCEDURE GetOrderAmount(
IN pOrderNumber INT
)
BEGIN
SELECT
SUM(quantityOrdered * priceEach)
FROM orderDetails
WHERE orderNumber = pOrderNumber;
END$$
DELIMITER ;
call GetOrderAmount(1001);
# MySQL IF Statement -------------------------------
/*
The IF-THEN statement allows you to execute a set of SQL
statements based on a specified condition.
The following illustrates the syntax of the IF-THEN statement:
IF condition THEN
statements;
END IF;
*/
##################### STP_1 ##########################
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL(10,2) DEFAULT 0;
SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;
IF credit > 50000 THEN
SET pCustomerLevel = 'PLATINUM';
END IF;
END$$
DELIMITER ;
CALL GetCustomerLevel(181, @level);
SELECT @level;
###################### STP_2 ########################
DROP PROCEDURE GetCustomerLevel;
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;
SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;
IF credit > 50000 THEN
SET pCustomerLevel = 'PLATINUM';
ELSE
SET pCustomerLevel = 'NOT PLATINUM';
END IF;
END$$
DELIMITER ;
CALL GetCustomerLevel(447, @level);
SELECT @level;
###################### STP_3 ########################
DROP PROCEDURE GetCustomerLevel;
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;
SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;
IF credit > 50000 THEN
SET pCustomerLevel = 'PLATINUM';
ELSEIF credit <= 50000 AND credit > 10000 THEN
SET pCustomerLevel = 'GOLD';
ELSE
SET pCustomerLevel = 'SILVER';
END IF;
END $$
DELIMITER ;
CALL GetCustomerLevel(547, @level);
SELECT @level;
# MySQL CASE Statement ---------------------------------
/*
Besides the IF statement, MySQL provides an alternative
conditional statement called the CASE statement for constructing
conditional statements in stored procedures. The CASE statements
make the code more readable and efficient.
CASE case_value
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
...
[ELSE else-statements]
END CASE;
*/
###################### STP_1 ########################
DELIMITER $$
CREATE PROCEDURE GetCustomerShipping(
IN pCustomerNUmber INT,
OUT pShipping VARCHAR(50)
)
BEGIN
DECLARE customerCountry VARCHAR(100);
SELECT
country
INTO customerCountry FROM
customers
WHERE
customerNumber = pCustomerNUmber;
CASE customerCountry
WHEN 'USA' THEN
SET pShipping = '2-day Shipping';
WHEN 'Canada' THEN
SET pShipping = '3-day Shipping';
ELSE
SET pShipping = '5-day Shipping';
END CASE;
END$$
###################### STP_2 ########################
DELIMITER ;
CALL GetCustomerShipping(412,@shipping);
SELECT @shipping;
DELIMITER $$
CREATE PROCEDURE GetDeliveryStatus(
IN pOrderNumber INT,
OUT pDeliveryStatus VARCHAR(100)
)
BEGIN
DECLARE waitingDay INT DEFAULT 0;
SELECT
DATEDIFF(requiredDate, shippedDate)
INTO waitingDay
FROM orders
WHERE orderNumber = pOrderNumber;
CASE
WHEN waitingDay = 0 THEN
SET pDeliveryStatus = 'On Time';
WHEN waitingDay >= 1 AND waitingDay < 5 THEN
SET pDeliveryStatus = 'Late';
WHEN waitingDay >= 5 THEN
SET pDeliveryStatus = 'Very Late';
ELSE
SET pDeliveryStatus = 'No Information';
END CASE;
END$$
DELIMITER ;
CALL GetDeliveryStatus(10100,@delivery);
select @delivery;
################################## DAY 5 ####################################
# Introduction to MySQL LOOP statement
/*
The LOOP statement allows you to execute one or more statements repeatedly.
Here is the basic syntax of the LOOP statement:
[begin_label:] LOOP
statement_list
END LOOP [end_label]
or
[label]: LOOP
...
-- terminate the loop
IF condition THEN
LEAVE [label];
END IF;
...
END LOOP;
*/
###################### STP_1 ########################
DROP PROCEDURE LoopDemo;
DELIMITER $$
CREATE PROCEDURE LoopDemo()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 1;
SET str = '';
loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
SELECT str;
END$$
DELIMITER ;
CALL LoopDemo();
# MySQL WHILE loop statement ----------------------
/*
The WHILE loop is a loop statement that executes
a block of code repeatedly as long as a condition is true.
Here is the basic syntax of the WHILE statement:
[begin_label:] WHILE search_condition DO
statement_list
END WHILE [end_label]
*/
CREATE TABLE calendars(
id INT AUTO_INCREMENT,
fulldate DATE UNIQUE,
day TINYINT NOT NULL,
month TINYINT NOT NULL,
quarter TINYINT NOT NULL,
year INT NOT NULL,
PRIMARY KEY(id)
);
select * from calendars;
###################### STP_1 ########################
DELIMITER $$
CREATE PROCEDURE InsertCalendar(dt DATE)
BEGIN
INSERT INTO calendars(
fulldate,
day,
month,
quarter,
year
)
VALUES(
dt,
EXTRACT(DAY FROM dt),
EXTRACT(MONTH FROM dt),
EXTRACT(QUARTER FROM dt),
EXTRACT(YEAR FROM dt)
);
END$$
DELIMITER ;
###################### STP_2 ########################
DELIMITER $$
CREATE PROCEDURE LoadCalendars(
startDate DATE,
day INT
)
BEGIN
DECLARE counter INT DEFAULT 1;
DECLARE dt DATE DEFAULT startDate;
WHILE counter <= day DO
CALL InsertCalendar(dt);
SET counter = counter + 1;
SET dt = DATE_ADD(dt,INTERVAL 1 day);
END WHILE;
END$$
DELIMITER ;
call LoadCalendars(curdate(), 30)
select curdate()
# MySQL REPEAT Loop -----------------
/*
The REPEAT statement executes one or more statements until a
search condition is true.
Here is the basic syntax of the REPEAT loop statement:
[begin_label:] REPEAT
statement
UNTIL search_condition
END REPEAT [end_label]
*/
DELIMITER $$
CREATE PROCEDURE RepeatDemo()
BEGIN
DECLARE counter INT DEFAULT 1;
DECLARE result VARCHAR(100) DEFAULT '';
REPEAT
SET result = CONCAT(result,counter,',');
SET counter = counter + 1;
UNTIL counter >= 10
END REPEAT;
-- display result
SELECT result;
END$$
DELIMITER ;
CALL RepeatDemo();
# MySQL LEAVE statement
/*
The LEAVE statement exits the flow control that has a given label.
The following shows the basic syntax of the LEAVE statement:
LEAVE label;
If the label is the outermost of the stored procedure or
function block, LEAVE terminates the stored procedure or function.
The following statement shows how to use the LEAVE statement
to exit a stored procedure:
CREATE PROCEDURE sp_name()
sp: BEGIN
IF condition THEN
LEAVE sp;
END IF;
-- other statement
END$$
*/
DELIMITER $$
CREATE PROCEDURE CheckCredit(
inCustomerNumber int
)
sp: BEGIN
DECLARE customerCount INT;
-- check if the customer exists
SELECT
COUNT(*)
INTO customerCount
FROM
customers
WHERE
customerNumber = inCustomerNumber;
-- if the customer does not exist, terminate
-- the stored procedure
IF customerCount = 0 THEN
LEAVE sp;
END IF;
-- other logic
-- ...
END$$
DELIMITER ;
# MySQL Stored Function ----------
/*
The following illustrates the basic syntax for creating a new stored function:
DELIMITER $$
CREATE FUNCTION function_name(
param1,
param2,…
)
RETURNS datatype
[NOT] DETERMINISTIC
BEGIN
-- statements
END $$
DELIMITER ;
A deterministic function always returns
the same result for the same input parameters whereas
a non-deterministic function returns different results for the same
input parameters.
If you don’t use DETERMINISTIC or NOT DETERMINISTIC,
MySQL uses the NOT DETERMINISTIC option by default.
*/
###################### Functioni_1 ########################
DELIMITER $$
CREATE FUNCTION CustomerLevel(
credit DECIMAL(10,2)
)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE customerLevel VARCHAR(20);
IF credit > 50000 THEN
SET customerLevel = 'PLATINUM';
ELSEIF (credit >= 50000 AND
credit <= 10000) THEN
SET customerLevel = 'GOLD';
ELSEIF credit < 10000 THEN
SET customerLevel = 'SILVER';
END IF;
-- return the customer level
RETURN (customerLevel);
END$$
DELIMITER ;
SELECT
customerName,
CustomerLevel(creditLimit)
FROM
customers
ORDER BY
customerName;
# creates a new stored procedure that calls the CustomerLevel() stored function:
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN customerNo INT,
OUT customerLevel VARCHAR(20)
)
BEGIN
DECLARE credit DEC(10,2) DEFAULT 0;
-- get credit limit of a customer
SELECT
creditLimit
INTO credit
FROM customers
WHERE
customerNumber = customerNo;
-- call the function
SET customerLevel = CustomerLevel(credit);
END$$
DELIMITER ;
CALL GetCustomerLevel(-131,@customerLevel);
SELECT @customerLevel;
# MySQL DROP FUNCTION ----------
# DROP FUNCTION [IF EXISTS] function_name;
########################### Mysql Triggers ###########################
/*
MySQL, a trigger is a stored program invoked automatically in response