NikhilDevS.B
nikhildevsb@gmail.com
www.facebook.com/nikhildevsb
TwitterProfile
www.linkedin.com/nikhildevsb
Typing speed: 24 wpm.
STORED PROCEDURE,CURSOR AND
TRANSACTIONS IN MySQL
Disclaimer: This presentation is prepared by trainees of
baabtra.com as a part of mentoring program. This is not
official document of baabtra.com – Mentoring Partner
STORED PROCEDURE
• A stored procedure is a method to encapsulate repetitive
tasks.
• A stored Procedure is actually stored in database data
dictionary.
• Can call and run from Database Environment
• Compiles only one time
Syntax:
DELIMITER //
CREATE PROCEDURE ProcedureName (MODE
Parameters Datatype) BEGIN
SQL Statements;
END //
Example :
delimiter //
CREATE PROCEDURE csp_gettotalsalaryatplace
(IN place varchar(20),OUT total int)
BEGIN
select sum(int_salary) into total from tbl_employee where
vchr_place=‘Mexico’;
END //
CALLING A Stored Procedure
CALL csp_ProcedureName(Parameters);
Example:
CALL csp_gettotalsalryatplace(‘Calicut’,@total);
select @total;
ADVANTAGES OF SP
• Pre-Compiled Execution : The Server compiles the SP
only once and Re-utilize it
• Reduced Client-Server Traffic : SP reduces the traffic
from Client by sending short SP calling statements
instead of whole vast SQL statements
• Efficient Re-Usability of Code : Once a SP stored in the
Database, it can be used by several Client Programs
CURSOR
• Control Structure that enables iterations over the records in a
Database
• Used to process individual Rows returned by the Queries
• It enables the rows in a result set to be processed sequentially
• It can be viewed as a pointer to one row in a set of rows
• Cursor can refer one Row at a time, but can be moved through the
Row Set
Synatx :
• Declaring a Cursor by DECLARE statement. Variable declaration must be done before
the declaration of the Cursor
DECLARE cursor_name CURSOR FOR SELECT_statement;
• OPEN : Opens a Cursor, that means, initializes the Result set (Row set) for the Cursor
OPEN cursor_name;
• FETCH : To retrieve the next Row pointed by the Cursor and move the Cursor to the
next Row in the Result set
FETCH cursor_name INTO variables list;
• CLOSE : When Cursor is no longer used, it must be closed
CLOSE cursor_name;
DATABASE TRANSACTIONS
? WHAT IS DATABASE TRANSACTIONS
• A database transactions is a unit of work that you want to
treat as “a whole”. It has to either happen in full, or not at all.
• Database transactions are logical units of work which must
all be performed to maintain data integrity
Transaction supports concurrency control..
 Many applications require a lot of users to access the data
simultaneously (e.g. airline booking systems)
 Uncontrolled simultaneous access can result in chaos, so some
controlling mechanism is required which provides by transaction.
It will probably be made up of smaller operations which
temporarily cause inconsistency
Need of Transaction...
E.g. Move money from one account to another.
T1. UPDATE tbl_accountA SET flt_balance = flt_balance – 100
WHERE int_accountNo = 123;
T2. UPDATE tbl_accountB SET flt_balance = flt_balance + 100
WHERE int_accountNo = 124;
Suppose system fails after Transaction T1, then amount 100
has been deducted from tbl_accountA but not credited in
tbl_accountB.
Peculiarities of Transactions
 No inconsistent state will arise.
 Transaction has only two states :
Either COMMIT (success) or ROLLBACK(fail) transaction. Which
means either complete the execution of statements(query) or leave if any error
occurs and undo all changes to begin-state.
 No data loss and no malicious data will arise.
 Assurance of data integrity.
 Manage recovery from system crashes.
Flow of a transaction
A transaction is the execution of a program that accesses the DB and
• starts with a BEGIN operation,
• followed by a sequence of READ and WRITE operations,
• ending with a COMMIT or ABORT operation.
ACID Properties of Transactions
ACID stands for:
• Atomicity
• Consistency
• Isolation
• Durability
Atomicity
- Each transaction be “all or nothing”.
- If one of transaction fails , the entire transaction fails.
- Including power failure, system crash.
- Committed transaction appears to be single(atomic).
Consistency
-Ensures that database remains consistent before the start of
transaction and after the transaction.
Isolation
-Each transaction is conserved i.e. , other operation can’t access
or see in an immediate state during a transaction.
-Each transaction is unaware of another transaction executing
concurrently in system.
Durability
-Once a transaction has done , it will persist, and not be undone.
-It survive system failure.
- It doesn’t imply permanent change , another transaction can
overwrite any change made by current transaction
Example: TRANSACTION IN STORED PROCEDURE.
[update bonus amount by 100 of employee whose age is greater than 50 and bonus>=1000]
DELIMITER //
CREATE PROCEDURE csp_chkAge()
BEGIN
DECLARE int_maxAge int; /* declare integer variable
int_maxAge */
START TRANSACTION; /*transaction starts here */
INSERT into tbl_status VALUES('Bonus set'); /*insert
‘Bonus set’ to tbl_status */
SELECT max(int_age) INTO int_maxAge FROM tbl_employee;
IF(int_maxAge>50) THEN
UPDATE tbl_employee SET int_bonus=int_bonus+100 WHERE
int_bonus>=1000; /*bonus increase by
1000 */
COMMIT;
ELSE
ROLLBACK; /* if age of employee less than 50 no change
will happen , transaction rollback, insertion in
tbl_status and updation in tbl_employee undo */
Pk_int_emp_id Vchr_emp_name Int_age Int_bonus
1 Johnson 35 900
2 Robert 28 850
3 Maxwell 55 1200
4 Steve 54 1100
tbl_employee
Pk_int_emp_id Vchr_emp_name Int_age Int_bonus
1 Johnson 35 900
2 Robert 28 850
3 Maxwell 55 1300
4 Steve 54 1200
after calling procedure csp_chkAge() and transaction commit
tbl_employee tbl_status
Vchr_status
Bonus set
Example: TRANSACTION WITH CURSOR
DELIMITER //
CREATE PROCEDURE csp_select()
BEGIN
DECLARE int_updtBonus int;
DECLARE bonus_cursor CURSOR FOR SELECT int_bonus
FROM tbl_employee where int_age >50 FOR UPDATE; /*declare
cursor for tbl_employee */
START TRANSACTION; /*transaction begins here
*/
OPEN bonus_cursor;
FETCH bonus_cursor INTO int_updtBonus; /*assign cursor
value to variable */
UPDATE tbl_employee SET int_bonus=int_bonus+100
WHERE int_updtBonus;
CLOSE bonus_cursor;
COMMIT;
Thank you...
Want to learn more about programming or Looking to become a good programmer?
Are you wasting time on searching so many contents online?
Do you want to learn things quickly?
Tired of spending huge amount of money to become a Software professional?
Do an online course
@ baabtra.com
We put industry standards to practice. Our structured, activity based courses are so designed
to make a quick, good software professional out of anybody who holds a passion for coding.
Follow us @ twitter.com/baabtra
Like us @ facebook.com/baabtra
Subscribe to us @ youtube.com/baabtra
Become a follower @ slideshare.net/BaabtraMentoringPartner
Connect to us @ in.linkedin.com/in/baabtra
Give a feedback @ massbaab.com/baabtra
Thanks in advance
www.baabtra.com | www.massbaab.com |www.baabte.com
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Cafit Square,
Hilite Business Park,
Near Pantheerankavu,
Kozhikode
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com
Contact Us

Sql transacation

  • 2.
  • 3.
    Disclaimer: This presentationis prepared by trainees of baabtra.com as a part of mentoring program. This is not official document of baabtra.com – Mentoring Partner
  • 4.
    STORED PROCEDURE • Astored procedure is a method to encapsulate repetitive tasks. • A stored Procedure is actually stored in database data dictionary. • Can call and run from Database Environment • Compiles only one time
  • 5.
    Syntax: DELIMITER // CREATE PROCEDUREProcedureName (MODE Parameters Datatype) BEGIN SQL Statements; END //
  • 6.
    Example : delimiter // CREATEPROCEDURE csp_gettotalsalaryatplace (IN place varchar(20),OUT total int) BEGIN select sum(int_salary) into total from tbl_employee where vchr_place=‘Mexico’; END //
  • 7.
    CALLING A StoredProcedure CALL csp_ProcedureName(Parameters); Example: CALL csp_gettotalsalryatplace(‘Calicut’,@total); select @total;
  • 8.
    ADVANTAGES OF SP •Pre-Compiled Execution : The Server compiles the SP only once and Re-utilize it • Reduced Client-Server Traffic : SP reduces the traffic from Client by sending short SP calling statements instead of whole vast SQL statements • Efficient Re-Usability of Code : Once a SP stored in the Database, it can be used by several Client Programs
  • 9.
    CURSOR • Control Structurethat enables iterations over the records in a Database • Used to process individual Rows returned by the Queries • It enables the rows in a result set to be processed sequentially • It can be viewed as a pointer to one row in a set of rows • Cursor can refer one Row at a time, but can be moved through the Row Set
  • 10.
    Synatx : • Declaringa Cursor by DECLARE statement. Variable declaration must be done before the declaration of the Cursor DECLARE cursor_name CURSOR FOR SELECT_statement; • OPEN : Opens a Cursor, that means, initializes the Result set (Row set) for the Cursor OPEN cursor_name; • FETCH : To retrieve the next Row pointed by the Cursor and move the Cursor to the next Row in the Result set FETCH cursor_name INTO variables list; • CLOSE : When Cursor is no longer used, it must be closed CLOSE cursor_name;
  • 11.
    DATABASE TRANSACTIONS ? WHATIS DATABASE TRANSACTIONS • A database transactions is a unit of work that you want to treat as “a whole”. It has to either happen in full, or not at all. • Database transactions are logical units of work which must all be performed to maintain data integrity
  • 12.
    Transaction supports concurrencycontrol..  Many applications require a lot of users to access the data simultaneously (e.g. airline booking systems)  Uncontrolled simultaneous access can result in chaos, so some controlling mechanism is required which provides by transaction. It will probably be made up of smaller operations which temporarily cause inconsistency
  • 13.
    Need of Transaction... E.g.Move money from one account to another. T1. UPDATE tbl_accountA SET flt_balance = flt_balance – 100 WHERE int_accountNo = 123; T2. UPDATE tbl_accountB SET flt_balance = flt_balance + 100 WHERE int_accountNo = 124; Suppose system fails after Transaction T1, then amount 100 has been deducted from tbl_accountA but not credited in tbl_accountB.
  • 14.
    Peculiarities of Transactions No inconsistent state will arise.  Transaction has only two states : Either COMMIT (success) or ROLLBACK(fail) transaction. Which means either complete the execution of statements(query) or leave if any error occurs and undo all changes to begin-state.  No data loss and no malicious data will arise.  Assurance of data integrity.  Manage recovery from system crashes.
  • 15.
    Flow of atransaction A transaction is the execution of a program that accesses the DB and • starts with a BEGIN operation, • followed by a sequence of READ and WRITE operations, • ending with a COMMIT or ABORT operation.
  • 16.
    ACID Properties ofTransactions ACID stands for: • Atomicity • Consistency • Isolation • Durability
  • 17.
    Atomicity - Each transactionbe “all or nothing”. - If one of transaction fails , the entire transaction fails. - Including power failure, system crash. - Committed transaction appears to be single(atomic).
  • 18.
    Consistency -Ensures that databaseremains consistent before the start of transaction and after the transaction. Isolation -Each transaction is conserved i.e. , other operation can’t access or see in an immediate state during a transaction. -Each transaction is unaware of another transaction executing concurrently in system.
  • 19.
    Durability -Once a transactionhas done , it will persist, and not be undone. -It survive system failure. - It doesn’t imply permanent change , another transaction can overwrite any change made by current transaction
  • 20.
    Example: TRANSACTION INSTORED PROCEDURE. [update bonus amount by 100 of employee whose age is greater than 50 and bonus>=1000] DELIMITER // CREATE PROCEDURE csp_chkAge() BEGIN DECLARE int_maxAge int; /* declare integer variable int_maxAge */ START TRANSACTION; /*transaction starts here */ INSERT into tbl_status VALUES('Bonus set'); /*insert ‘Bonus set’ to tbl_status */ SELECT max(int_age) INTO int_maxAge FROM tbl_employee; IF(int_maxAge>50) THEN UPDATE tbl_employee SET int_bonus=int_bonus+100 WHERE int_bonus>=1000; /*bonus increase by 1000 */ COMMIT; ELSE ROLLBACK; /* if age of employee less than 50 no change will happen , transaction rollback, insertion in tbl_status and updation in tbl_employee undo */
  • 21.
    Pk_int_emp_id Vchr_emp_name Int_ageInt_bonus 1 Johnson 35 900 2 Robert 28 850 3 Maxwell 55 1200 4 Steve 54 1100 tbl_employee Pk_int_emp_id Vchr_emp_name Int_age Int_bonus 1 Johnson 35 900 2 Robert 28 850 3 Maxwell 55 1300 4 Steve 54 1200 after calling procedure csp_chkAge() and transaction commit tbl_employee tbl_status Vchr_status Bonus set
  • 22.
    Example: TRANSACTION WITHCURSOR DELIMITER // CREATE PROCEDURE csp_select() BEGIN DECLARE int_updtBonus int; DECLARE bonus_cursor CURSOR FOR SELECT int_bonus FROM tbl_employee where int_age >50 FOR UPDATE; /*declare cursor for tbl_employee */ START TRANSACTION; /*transaction begins here */ OPEN bonus_cursor; FETCH bonus_cursor INTO int_updtBonus; /*assign cursor value to variable */ UPDATE tbl_employee SET int_bonus=int_bonus+100 WHERE int_updtBonus; CLOSE bonus_cursor; COMMIT;
  • 23.
  • 24.
    Want to learnmore about programming or Looking to become a good programmer? Are you wasting time on searching so many contents online? Do you want to learn things quickly? Tired of spending huge amount of money to become a Software professional? Do an online course @ baabtra.com We put industry standards to practice. Our structured, activity based courses are so designed to make a quick, good software professional out of anybody who holds a passion for coding.
  • 25.
    Follow us @twitter.com/baabtra Like us @ facebook.com/baabtra Subscribe to us @ youtube.com/baabtra Become a follower @ slideshare.net/BaabtraMentoringPartner Connect to us @ in.linkedin.com/in/baabtra Give a feedback @ massbaab.com/baabtra Thanks in advance www.baabtra.com | www.massbaab.com |www.baabte.com
  • 26.
    Emarald Mall (BigBazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Cafit Square, Hilite Business Park, Near Pantheerankavu, Kozhikode Start up Village Eranakulam, Kerala, India. Email: info@baabtra.com Contact Us