-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql-advance.sql
More file actions
1450 lines (1025 loc) · 31 KB
/
sql-advance.sql
File metadata and controls
1450 lines (1025 loc) · 31 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
#------------{ Advance SQL }---------------------------
/**
* @Author -> Amol Dhawale
* @Since -> December 2022
* @Note -> This will explain advance sql concepts in mysql
* @Contact -> amoldlive@gmail.com | 7276466779
* @Linkedin -> amoldhawale
*/
#-----------Required Data Builder----------------------
create database advancedb;
use advancedb;
CREATE TABLE customers (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(50),
phone_number varchar(10)
);
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
order_details varchar(50),
order_date DATE,
amount DECIMAL(8,2),
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
INSERT INTO customers (first_name, last_name, email,phone_number)
VALUES ('Rahul', 'Mishra', 'rm@gmail.com','7878457845'),
('Vishal', 'Varma', 'vv@gmail.com','4556788945'),
('Rohan', 'Trivedi', 'rt@gmail.com','1245784512'),
('John', 'Steele', 'js@gmail.com','4578457845'),
('Arun', 'Patel', 'ap@gmail.com','1278457845');
select * from customers ;
INSERT INTO orders (order_details, order_date, amount, customer_id)
VALUES ('Oil','2022-02-10', 99.99, 1),
('soap','2022-11-11', 35.50, 1),
('fortune rice 5kg','2022-12-12', 800.67, 2),
('pen','2022-01-03', 12.50, 2),
('Vim Liquid 2L','2022-04-11', 450.25, 5),
('Vim Bar','2022-04-11', 65.25, 3),
('Cello Bottle','2022-04-11', 450.25, 3),
('Face Wash','2022-04-11', 45.25, 4);
select * from orders ;
#------------views-------------------------------------
/* the View is a virtual table created by a query by joining one or more tables */
/*-------------Create----------------------------------*/
/*syntax*/
-- CREATE [OR REPLACE] VIEW view_name AS
-- SELECT columns
-- FROM tables
-- [WHERE conditions];
select * from customers ;
select id,first_name ,last_name from customers ;
create view customers_view1 as
select id ,first_name ,last_name from customers ;
select * from customers_view1 ;
create view customers_order_view as
select
customers.id ,customers.first_name ,customers.last_name,
orders.order_details ,orders.amount
from customers inner join orders
where customers.id =orders.customer_id ;
select * from customers_order_view ;
/*with OR Replace*/
create or replace view customers_view1 as
select id ,first_name from customers ;
select * from customers_view1 ;
/*-------------Update----------------------------------*/
/*Syntax*/
/*
ALTER VIEW view_name AS
SELECT columns
FROM table
WHERE conditions;
*/
alter view customers_view1 as
select id ,first_name,last_name from customers
where id in (1,2,3);
select * from customers_view1;
/*-------------Show Views----------------------------------*/
SHOW FULL TABLES IN advancedb WHERE TABLE_TYPE LIKE 'VIEW';
/*-------------Drop----------------------------------*/
/*Syntax*/
/*DROP VIEW [IF EXISTS] customers_view1; */
DROP VIEW customers_view1;
DROP VIEW customers_view1;
DROP VIEW IF EXISTS customers_view1;
#------------Stored Procedures-------------------------------------
/*A procedure (often called a stored procedure) is a collection of pre-compiled SQL statements stored inside the database.*/
/*Syntax*/
/*
DELIMITER $$
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name datatype [, parameter datatype]) ]
BEGIN
Declaration_section
Executable_section
END $$
DELIMITER ;
*/
select * from customers ;
select * from orders;
/* Delimeter - > default ; */
DELIMITER delimiter_character
DELIMITER $$ -- channging default delimeter
/*Syntax --> Creating Simple Procedures*/
DELIMITER $$
CREATE PROCEDURE stored_procedure_name()
BEGIN
-- statements
END $$
DELIMITER ; -- change it to default
/*calling stored procedures */
CALL stored_procedure_name();
/*Creating 1st procedure */
DELIMITER $$
CREATE PROCEDURE customer_sp()
BEGIN
select * from customers;
END $$
DELIMITER ;
/*calling procedures*/
call customer_sp;
call customer_sp();
/*Creating procedure with argument*/
DELIMITER $$
CREATE PROCEDURE customer_arg_sp(in cust_id int)
BEGIN
select * from customers where id=cust_id;
END $$
DELIMITER ;
/*calling procedure with argument*/
call customer_arg_sp(1);
call customer_arg_sp(2);
#------------Show Procedures-------------------------------------
/*Syntax*/
/*SHOW PROCEDURE STATUS [LIKE 'pattern' | WHERE search_condition]*/
SHOW PROCEDURE STATUS;
SHOW PROCEDURE STATUS like 'cust%';
SHOW PROCEDURE STATUS where db='advancedb';
#------------Alter Stored Procedures-------------------------------------
/*
To make such changes, you must drop ad re-create the stored procedure
using the DROP PROCEDURE and CREATE PROCEDURE statements.
*/
#------------Removing stored procedure-------------------------------------
DROP PROCEDURE [IF EXISTS] stored_procedure_name;
DROP PROCEDURE customer_sp;
DROP PROCEDURE customer_sp;
DROP procedure if exists customer_sp;
#------------Check stored procedure Defination-------------------------------------
show create procedure <procedure_name>;
show create procedure customer_arg_sp;
#------------Stored Procedure Variable-------------------------------------
DECLARE variable_name datatype(size) [DEFAULT default_value];
/*
Desclare -> declare variable
datatype -> data type of the variable
default -> default value assigned to variable
*/
/*Assigning variable value*/
SET variable_name = value;
DECLARE total INT DEFAULT 0;
SET total = 10;
/* Constants */
SET @counter = 1;
/*Accessing Constants */
select @counter;
#------------Using variables-------------------------------------
DELIMITER $$
CREATE PROCEDURE testVariable()
BEGIN
DECLARE a INT DEFAULT 0;
DECLARE b INT DEFAULT 0;
DECLARE c INT DEFAULT 0;
set a=50;
set b=50;
set c=a+b;
select c;
END$$
DELIMITER ;
call testVariable();
DELIMITER $$
CREATE PROCEDURE addition(in num1 int,in num2 int)
BEGIN
DECLARE addition INT DEFAULT 0;
set addition=num1+num2;
select addition;
END$$
DELIMITER ;
call addition(5,5);
call addition(5,50);
call addition(15,25);
DELIMITER $$
CREATE PROCEDURE getTotalCustomers()
BEGIN
DECLARE totalCustomers INT DEFAULT 0;
select count(*) into totalCustomers from customers ;
select totalCustomers;
END$$
DELIMITER ;
call getTotalCustomers();
/*Assignment
* -> implement store procedure which can take 2 inputs and perform substraction
* * -> implement store procedure which can take 2 inputs and perform multiplication
* * -> implement store procedure which can take 5 inputs and perform total /average operation
*
* */
#------------Drop All Procedures from DB-------------------------------------
SELECT
CONCAT('DROP ',ROUTINE_TYPE,' `',ROUTINE_SCHEMA,'`.`',ROUTINE_NAME,'`;') as stmt
FROM information_schema.ROUTINES where ROUTINE_SCHEMA='advancedb';
#------------Parameters-------------------------------------
[IN | OUT | INOUT] parameter_name datatype[(length)]
/*IN Parameter*/
DELIMITER $$
CREATE PROCEDURE getOrders(in custId int)
BEGIN
select * from orders where customer_id =custId;
END$$
DELIMITER ;
call getOrders(1) ;
call getOrders(2) ;
call getOrders(0) ;
/*OUT Parameter*/
DELIMITER $$
create procedure addition(in num1 int,in num2 int,out result int)
begin
set result=num1+num2;
end $$
DELIMITER ;
set @addresult=0;
call addition(10,12,@addresult);
select @addresult;
call addition(15,12,@addresult);
select @addresult;
select sqrt(16);
DELIMITER $$
DROP PROCEDURE IF exists GET_SQRT$$
CREATE PROCEDURE GET_SQRT(in num INT, OUT sqrt_result FLOAT)
begin
SET sqrt_result=SQRT(num);
END$$
DELIMITER ;
set @result=0;
call GET_SQRT(16,@result);
select @result;
/*example 2*/
DELIMITER $$
DROP PROCEDURE IF exists cust_count_sp$$
CREATE PROCEDURE cust_count_sp(OUT cust_count FLOAT)
begin
select count(*) into cust_count from customers;
END$$
DELIMITER ;
set @cust_count=0;
call cust_count_sp(@cust_count);
select @cust_count;
/*INOUT Parameter*/
DELIMITER $$
DROP PROCEDURE IF exists mycounter$$
CREATE PROCEDURE mycounter( INOUT counter INT, IN inc INT )
BEGIN
SET counter = counter + inc;
END$$
DELIMITER ;
SET @counter = 1;
select @counter;
CALL mycounter(@counter,1); -- 2
select @counter;
CALL mycounter(@counter,1); -- 3
select @counter;
CALL mycounter(@counter,5); -- 8
select @counter;
#------------IF-THEN [IF-ELSE] -------------------------------------
/*
The IF statement has three forms:
1. simple IF-THEN statement,
2. IF-THEN-ELSE statement,
3. IF-THEN-ELSEIF- ELSE statement.
*/
/*Simple IF-THEN */
/*IF condition THEN
statements;
END IF;*/
DELIMITER $$
drop procedure if exists testIfThen$$
create PROCEDURE testIfThen(IN switch INT)
BEGIN
if switch=1 then
select "I am in if block";
end if;
END$$
DELIMITER ;
call testIfThen(1);
call testIfThen(0);
call testIfThen(5);
DELIMITER $$
drop procedure if exists testIfThen$$
create PROCEDURE testIfThen(IN num INT)
BEGIN
DECLARE i int;
set i= 10 ;
if num>0 then
set i= i+num;
end if;
select i;
END$$
DELIMITER ;
call testIfThen(1);
call testIfThen(2);
call testIfThen(3);
call testIfThen(4);
/*find is number is positive*/
DELIMITER $$
drop procedure if exists checkPositiveNumber$$
create PROCEDURE checkPositiveNumber(IN num INT)
BEGIN
if num>0 then
select concat("Number ",num,' is positive');
end if;
END$$
DELIMITER ;
call checkPositiveNumber(1);
call checkPositiveNumber(2);
call checkPositiveNumber(0);
#------------IF-THEN-ELSE-------------------------------------
/*
IF condition THEN
statements;
ELSE
else-statements;
END IF;
*/
/*find is number is positive or negative*/
DELIMITER $$
create PROCEDURE findNumberState(in num int)
BEGIN
if num>0 then
select concat("Number ",num,' is positive');
else
select concat("Number ",num,' is negative');
end if;
END$$
DELIMITER ;
call findNumberState(3);
call findNumberState(-3);
/*get table data on the basis of character*/
DELIMITER $$
create PROCEDURE getData(in dataSelector varchar(1))
BEGIN
if dataSelector='c' || dataSelector='C' then
select * from customers;
else
select * from orders;
end if;
END$$
DELIMITER ;
call getData('c');
call getData('C');
call getData('o');
call getData('a');
#------------IF-THEN-ELSEIF-------------------------------------
/*IF condition THEN
statements;
ELSEIF elseif-condition THEN
elseif-statements;
...
ELSE
else-statements;
END IF;*/
/*find the number is positive , negative or zero*/
DELIMITER $$
drop procedure if exists findNumberState$$
create PROCEDURE findNumberState(in num int)
BEGIN
if num>0 then
select concat("Number ",num,' is positive');
elseif num<0 then
select concat("Number ",num,' is negative');
else
select concat("Number ",num,' is zero');
end if;
END$$
DELIMITER ;
call findNumberState(3);
call findNumberState(-3);
call findNumberState(0);
#------------CASE-WHEN-------------------------------------
/*CASE case_value
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
...
[ELSE else-statements]
END CASE;*/
/*Task - Print name of day*/
DELIMITER $$
create PROCEDURE printDayName(in dayNum int)
BEGIN
case dayNum
when 1 then
select "Sunday";
when 2 then
select "Monday";
when 3 then
select "Tuesday";
when 4 then
select "Wednesday";
when 5 then
select "Thursday";
when 5 then
select "Friday";
when 6 then
select "Saturday";
else
select "invalid day number";
end case;
END$$
DELIMITER ;
call printDayName(1);
call printDayName(3);
call printDayName(7);
/*Assignment :create case to print month name on the basis of month number*/
DELIMITER $$
create PROCEDURE printAlphabet(in alphabet varchar(1))
BEGIN
case alphabet
when 'a' then
select "This is a";
when 'b' then
select "This is b";
when 'c' then
select "This is c";
else
select "invalid alphabet";
end case;
END$$
DELIMITER ;
call printAlphabet('a');
call printAlphabet('c');
call printAlphabet('#');
DELIMITER $$
create PROCEDURE getMyData(in tableNum int,in inputId int)
BEGIN
case tableNum
when 1 then
select * from customers where id =inputId ;
when 2 then
select * from orders where id =inputId ;
else
select "invalid table number";
end case;
END$$
DELIMITER ;
call getMyData(1,1);
call getMyData(1,2);
call getMyData(2,1);
call getMyData(2,3);
#------------Loop-------------------------------------
/*[begin_label:] LOOP
statement_list
[ leave / iterate ] begin_label
END LOOP [end_label]*/
#----------break/continue-------------
# leave label | Iterate Label
DELIMITER $$
create PROCEDURE printNumber()
begin
declare num int;
declare str varchar(50);
set num=1;
set str='';
print_label: loop
if num>10 then
leave print_label;
end if;
set str=concat(str,num,',');
set num=num+1;
end loop print_label;
select str;
END$$
DELIMITER ;
call printNumber();
#---------------------------------------------------------
drop procedure if exists printNumberSkipTillFive;
DELIMITER $$
create PROCEDURE printNumberSkipTillFive()
begin
declare num int;
declare str varchar(50);
set num=0;
set str='';
print_label: loop
if num>10 then
leave print_label;
end if;
set num=num+1;
if num<=5 then
iterate print_label;
end if;
if num<=10 then
set str=concat(str,num,',');
end if;
end loop print_label;
select str;
END$$
DELIMITER ;
call printNumberSkipTillFive();
/*Assignment :
* Print 10 to 1 numbers
* Print even numbers between 1 to user given number
* Calculate factorial of users gien number
* */
#------------While Loop-------------------------------------
/*[begin_label:] WHILE search_condition DO
statement_list
END WHILE [end_label]*/
drop procedure printNumberWhile;
DELIMITER $$
create PROCEDURE printNumberWhile()
begin
declare num int;
declare str varchar(50);
set num=1;
set str='';
my_label: while num<=10 do
set str=concat(str,num,',');
set num=num+1;
end while my_label;
select str;
END$$
DELIMITER ;
call printNumberWhile();
/*Assignment using while :
* print 1 to users given number incliding their sum : O/P 1,2,3 | 6 : in -> 5 o/p 1 2 3 4 5 | 15
* print fabonnacci series till users gien number
* */
#------------Repeat Loop [similar to inverse conditional do-while loop]-------------------------------------
/*[begin_label:] REPEAT
statement
UNTIL search_condition
END REPEAT [end_label]*/
-- breaks loop when condition gets true
drop procedure printNumberRepeat;
DELIMITER $$
create PROCEDURE printNumberRepeat()
begin
declare num int;
declare str varchar(50);
set num=1;
set str='';
my_label:Repeat
set str=concat(str,num,',');
set num=num+1;
until num>10 -- breaks loop when condition gets true
end repeat my_label;
select str;
END$$
DELIMITER ;
call printNumberRepeat();
#------------LEAVE [similar to break]-------------------------------------
DELIMITER $$
create PROCEDURE getNumber(in num int)
mysp_label:begin
if num=0 then
leave mysp_label; -- breaking sp
end if;
select num;
END$$
DELIMITER ;
call getNumber(1);
call getNumber(2);
call getNumber(0);
#------------Cursor [similar to resultset]-------------------------------------
/*To handle a result set inside a stored procedure, you use a cursor.
* A cursor allows you to iterate a set of rows returned by a query and process each row individually.
*/
/*
* MySQL cursor is read-only, non-scrollable and asensitive.
*
* Read-only: you cannot update data in the underlying table through the cursor.
* Non-scrollable: you can only fetch rows in the order determined by the SELECT statement. You cannot fetch rows in the reversed order. In addition, you cannot skip rows or jump to a specific row in the result set.
* Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of data.
*
*/
/* Steps to create and use cursors
* -------------------------------------
* 1. DECLARE cursor_name CURSOR FOR SELECT_statement;
* 2. DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
* 3. OPEN cursor_name;
* 4. FETCH cursor_name INTO variables list;
* 5. CLOSE cursor_name;
* --------------------------------------
*/
select * from customers ;
select concat("[" , first_name , " " , last_name , "]") from customers
select CONCAT("[Vishal Varma] " , "[Rahul Mishra]" );
/*TASK : get customer details list */
drop procedure if exists processCustomerData;
DELIMITER $$
create PROCEDURE processCustomerData(
INOUT customerDetailsList varchar(500))
begin
DECLARE finished INTEGER DEFAULT 0;
DECLARE customerdetails varchar(500) DEFAULT '';
/*declare cursor*/
DECLARE cursor_customer CURSOR FOR select concat("[" , first_name , " " , last_name , "]") from customers;
/* declare NOT FOUND handler*/
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
/*Open Cursor*/
OPEN cursor_customer;
custdata_sp: loop
/*Fetch details in cursor*/
FETCH cursor_customer INTO customerdetails;
IF finished = 1 THEN
LEAVE custdata_sp;
END IF;
SET customerDetailsList = CONCAT(customerdetails," , ",customerDetailsList);
end loop custdata_sp;
/*close cursore*/
close cursor_customer;
END$$
DELIMITER ;
set @customerDetailsList='';
call processCustomerData(@customerDetailsList);
select @customerDetailsList;
/*Assignment :
* get customers phone number and send 'Thank you for contacting with us' message
*
* table message -> column : id autoincrement PK ,phone_number , message , status default NO
*
* insert into message (phone number , message)
* */
#------------Error Handling [similar to try-catch]-------------------------------------
/*
* When an error occurs inside a stored procedure,
* it is important to handle it appropriately,
* such as continuing or exiting the current code block’s execution,
* and issuing a meaningful error message.
*/
/* ----------------------------------------------------------
* DECLARE action HANDLER FOR condition_value statement;
* -----------------------------------------------------------
*/
/*
* If a condition whose value matches the condition_value ,
* MySQL will execute the statement and continue or exit the current code block based on the action .
*
* The action accepts one of the following values:
* -----------------------------------------------
* CONTINUE : the execution of the enclosing code block ( BEGIN … END ) continues.
* EXIT : the execution of the enclosing code block, where the handler is declared, terminates.
*
* A MySQL error code.
* --------------------
* A standard SQLSTATE value. Or it can be an SQLWARNING , NOTFOUND or SQLEXCEPTION condition,
* which is shorthand for the class of SQLSTATE values.
* The NOTFOUND condition is used for a cursor or SELECT INTO variable_list statement.
*
*/
/* Sample to declare handler */
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET hasError = 1;
/* Sample to declare handler */
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET RowNotFound = 1;
/* Sample to declare handler */
DECLARE CONTINUE HANDLER FOR 1062
SELECT 'Error, duplicate key occurred';
#SQLState Codes
#https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-error-sqlstates.html
drop table person ;
create table person(
id int,
first_name varchar(50),
last_name varchar(50),
primary key(id,first_name,last_name)
);
insert into person values(1,'Rahul' ,'Varma');
insert into person values(2,'Soham' ,'Jha');
select * from person ;
insert into person values(1,'Rahul' ,'Varma');
drop procedure if exists InsertPerson;
DELIMITER $$
CREATE PROCEDURE InsertPerson( IN pid INT, IN pfirst_name varchar(50), IN plast_name varchar(50))
BEGIN
INSERT INTO person(id,first_name,last_name) VALUES(pid,pfirst_name,plast_name);
select concat(id,'-',first_name,'-',last_name) as person_details from person where id=pid;
END$$
DELIMITER ;
call InsertPerson(1,'Rohan','Shende');
call InsertPerson(1,'Rohan','Shende');
# [1062] [23000]: Duplicate entry '1-Rohan-Shende' for key 'person.PRIMARY'
#------------------------------------------------------------------
drop procedure if exists InsertPerson;
DELIMITER $$
CREATE PROCEDURE InsertPerson(
IN pid INT,
IN pfirst_name varchar(50),
IN plast_name varchar(50)
)
BEGIN
DECLARE EXIT HANDLER FOR 1062
-- BEGIN
SELECT CONCAT('My Exception -> Duplicate key ( ',pid,'-',pfirst_name,'-',plast_name,' ) occurred , Please add valid data ') AS message;
-- END
INSERT INTO person(id,first_name,last_name) VALUES(pid,pfirst_name,plast_name);
select concat(id,'-',first_name,'-',last_name) as person_details from person where id=pid;
END$$
DELIMITER ;
call InsertPerson(1,'Rohan','Shende');
#------------Raising Errors [similar to throw]-------------------------------------