introduction to mysql part 3

33
Recall • When to use group by? • Difference between ‘having’ and ‘where’? • Difference between scalar and aggregate functions? • What are the different types of joins?

Upload: baabtracom-first-coding-school-in-india

Post on 24-May-2015

529 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: Introduction to mysql part 3

Recall

• When to use group by?• Difference between ‘having’ and

‘where’?• Difference between scalar and

aggregate functions?• What are the different types of

joins?

Page 2: Introduction to mysql part 3

Introduction To DBMS and MySQLStored Procedures

Week 6 – Day1

Page 3: Introduction to mysql part 3

Stored Procedures

• A stored procedure is a method to encapsulate repetitive tasks.

• A stored Procedure is actually stored in database data dictionary

Page 4: Introduction to mysql part 3

Without Stored Procedure

Employee.jsp......................

Select * from tbl_employee ................

Report.php..........................

Select * from tbl_employee .................

.....................Select * from tbl_employee

viewDetails.php...................................................

Select * from tbl_employee

...............Database

Select * from tbl_employee

Select * from tbl_employee

Select * from tbl_employee

Page 5: Introduction to mysql part 3

Stored Procedure

Employee.php....................................................Call getName();

................

Report.php............................................................................. Call getName();

viewDetails.php...................................................Call getName();

...............

getName()BeginSelect * from tbl_employee End

Database

Page 6: Introduction to mysql part 3

Advantages• Precompiled Execution

• Mysql compiles each stored procedure once and then reutilizes the execution plan. This result in tremendous performance boosts when stored procedures are called repeatedly

• Reduced client server traffic• If network traffic is concerned you will be happy to learn that stored procedures can reduce long sql queries to a single line that is transmitted between application program and database server.

Page 7: Introduction to mysql part 3

Advantages• Efficient reuse of code and programming

abstraction• Stored procedures can be used by multiple programs and users. If you utilize them in a planned manner, you’ll find the development cycle takes less time.

• Enhanced Security Control• You can grant users permission to execute stored procedure independently of underlying table permissions

Page 8: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName(IN id int)

BEGINSelect * from tbl_user where userid=id;

ENDDelimiter ;

Call getName(‘1001’);

Page 9: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName(IN id int)

BEGINSelect * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

By default the delimiter is “;” . That means if you want the sever to start compiling of your sql query, you must put “;” and then press “enter”.

Delimiter // statement changes the default delimiter to “//” so that giving “;” inside store procedure will not push server to start compilation

Page 10: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName(IN id int)

BEGINSelect * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Is the keyword to create a new stored procedure

Page 11: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName(IN id int)

BEGINSelect * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Is the name of the stored procedure that we are creating

Page 12: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName ( IN id

int)BEGIN

Select * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Is the parameter list (here intiger type variable called “id”)

IN -> passing value into the stored procedure

Out -> returning value out of stored procedure

INOUT -> Same variable can be used to send in and out of stored procedure

Page 13: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName ( IN id

int)BEGIN

Select * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Is the keyword to begin the block of codes inside the stored functionIt’s same as curly brace ‘{‘ we use for functions in C

Page 14: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName ( IN id

int)BEGIN

Select * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Is the body of the stored procedure. Here we have only a single select query statements. We can also apply logic using the below • DECLARE a INT; : declaring an integer

type variable

• SET a=20; : Setting value of a to 20

• IF THEN• ELSE IF

label1: LOOP SET p1 = p1 + 1; IF p1 < 10 THEN ITERATE label1; END IF; LEAVE label1; END LOOP label1;

: For conditions

: Loops

Page 15: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName ( IN id

int)BEGIN

Select * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

End // -> the compiler starts compiling after you press enter. This is because “//” is the delimiter

Page 16: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName ( IN id

int)BEGIN

Select * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Now we are changing the delimiter back to “;”

Page 17: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getName ( IN id

int)BEGIN

Select * from tbl_user where userid=id;

END//Delimiter ;

Call getName(‘1001’);

Calling the stored procedure we’ve just created and passing the value 1001 as its argument

Page 18: Introduction to mysql part 3

How to create Stored Procedure ? example

Delimiter //CREATE PROCEDURE getSale ( IN id

int,OUT sale int,OUT aver int)BEGIN

Select sum(price) into sale,avg(price) into aver from tbl_purchase where deptid=id;

END//Delimiter ;

Call getSale(1001,@sale,@aver);Select @sale;Select @aver;

Page 19: Introduction to mysql part 3

• Create the below table

• Create a stored procedure called – csp_getSalary(1000) : should return the

salary of employee with id as passed in the argument

– Csp_getSalaryAtPlace(‘calicut’,@total) : should return the total salary of employees from a perticular place

Live Task

Tbl_employeeEmp_id Emp_name Emp_age Emp_email int_salary vchr_place

1000 Deepak 24 [email protected] 10000 Calicut

1001 Aneesh 23 [email protected] 20000 Cochin

1002 Naveen 25 [email protected] 10000 Calicut

1003 Jacob 25 [email protected] 30000 Cochin

Page 20: Introduction to mysql part 3

Cursors

• SELECT INTO is fine for single-row queries, but many applications require the querying of multiple rows of data. You will use a cursor in MySQL to accomplish this.

• A cursor lets you fetch one or more rows from a SQL result set into stored program variables, usually with the intention of performing some row-by-row processing on the result set.

Page 21: Introduction to mysql part 3

Cursors - exampleCreate procedure changePlace()Begin

DECLARE empId INT;DECLARE placeId VARCHAR(50);DECLARE done INT DEFAULT 0;DECLARE myCur CURSOR FOR SELECT emp_id,vchr_place from tbl_employees;DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;OPEN myCur;Emp_Loop: LOOPFETCH myCur INTO empId, placeId;If done=1 THENLEAVE Emp_loopElse iterate emp_loopENDIFEND LOOP emp_loopCLOSE myCur ;

END//

Page 22: Introduction to mysql part 3

Declare Handler• The DECLARE ... HANDLER statement

specifies a handler that deals with one or more conditions. If one of these conditions occurs, the specified statement executes.

• DECLARE handler_action HANDLER FOR condition_value [, condition_value] ... Statement

– handler_action: – CONTINUE | EXIT | UNDO

– condition_value: mysql_error_code – SQLWARNING | NOT FOUND | SQLEXCEPTION

Page 23: Introduction to mysql part 3

Questions?“A good question deserve a

good grade…”

Page 24: Introduction to mysql part 3

Self Check !!

Page 25: Introduction to mysql part 3

• Why should someone use stored procedure?

–To avoid data redundancy–To reduce network traffic between

application server and database server–To ensure data integrity

Self Check !!

Page 26: Introduction to mysql part 3

• Why should someone use stored procedure?

–To avoid data redundancy–To reduce network traffic between

application server and database server–To ensure data integrity

Self Check !!

Page 27: Introduction to mysql part 3

Self Check !!

• Why should someone change the delimiter before creating a stored procedure?

– To use ; as seperation between multiple statements in a stored procedure body

– To push the server to compile the whole body of stored procedure all together

– Both of above– None of above

Page 28: Introduction to mysql part 3

Self Check !!

• Why should someone change the delimiter before creating a stored procedure?

– To use ; as seperation between multiple statements in a stored procedure body

– To push the server to compile the whole body of stored procedure all together

– Both of above– None of above

Page 29: Introduction to mysql part 3

Self Check !!

CREATE PROCEDURE simpleProc ( OUT param1 INT)

BEGIN SELECT COUNT(*) INTO param1 FROM

t ;END

CALL simpleProc(@a);Select @a ;

Page 30: Introduction to mysql part 3

Self Check !!

CREATE PROCEDURE simpleProc ( OUT param1 INT)

BEGIN SELECT COUNT(*) INTO param1 FROM

t ;END

CALL simpleProc(@a);Select @a ;

Page 31: Introduction to mysql part 3

Self Check !!

•What are the uses of cursors?

• For extracting multiple rows from a table• For extracting multiple rows into variables from a table• For setting handlers

Page 32: Introduction to mysql part 3

Self Check !!

•What are the uses of cursors?

• For extracting multiple rows from a table• For extracting multiple rows into variables from a table• For setting handlers

Page 33: Introduction to mysql part 3

End of day