Sei sulla pagina 1di 35

Unit 6: Programming with MySQL

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Overview
Variables Flow control constructs
IF THEN ELSE CASE LOOP WHILE REPEAT UNTIL

Procedures Functions Triggers Cursors

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VARIABLES
You can store a value in a user-defined variable in one statement and then refer to it later in another statement This enables you to pass values from one statement to another User variables are written as @var_name, where the variable name var_name consists of alphanumeric and the special character _

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VARIABLES
Syntax:
DECLARE @varname1, @varname2, ... data type [DEFAULT value];

For Ex:
DECLARE @Student_Id int; DECLARE @Sname, @Cname varchar(15);

Variable assignment
For variable assignments, use either SET or SELECT SET @Sname = Krishna; SELECT @Sname := Name FROM Students WHERE StudentId = 1001;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VARIABLES
For SET, either = or := can be used as the assignment operator. For statements other than SET := must be used since = is treated as a comparison operator

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


Flow Control Constructs include the IF, CASE, LOOP, WHILE, ITERATE, REPEAT and LEAVE constructs These constructs can contain single statement or a block of statements using BEGIN..END statement. These constructs can be nested also.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


IF Statement
Syntax IF search_condition THEN statement_list ELSE IF search_condition THEN statement_list ELSE statement_list END IF

For Ex:
IF @CourseId = 1 THEN SET @Fees = 1000;
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


CASE Statement
Syntax CASE case_value WHEN when_value THEN statement_list [WHEN when_value THEN statement_list] statement_list] END CASE Or CASE WHEN search_condition THEN statement_list [WHEN search_condition THEN statement_list] ... [ELSE statement_list] END CASE
Copyright 2010 Pratian Technologies www.pratian.com

...

[ELSE

Basic SQL

FLOW CONTROL CONSTRUCTS


For Ex:
DECLARE @shipping_cost INT(2) DEFAULT 0; DECLARE @delivery_day INT(2) DEFAULT 0; SET @delivery_day := DAYOFWEEK(CURDATE()); CASE @delivery_day WHEN 1 THEN SET @shipping_cost = 20; WHEN 2 THEN SET @shipping_cost = 15; WHEN 3 THEN SET @shipping_cost = 10; ELSE SET @shipping_cost = 5; END CASE;
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


LOOP Statement Implements a simple loop construct is used to repeat execution of the statement_list, statement_list can contain one or more than one statements. Loop is exited with a LEAVE Statement

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


Loop Syntax
[begin_label:] LOOP statement_list END LOOP [end_label]

For Ex:
DECLARE @counter INT DEFAULT 0; simple_loop: LOOP SET @counter = @counter+1; SELECT @counter; IF @counter>=10 THEN LEAVE simple_loop; ELSEIF MOD(@counter, 2) = 0 THEN ITERATE simple_loop; END IF; SELECT @counter; END LOOP simple_loop;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


WHILE Statement The WHILE Statement repeats the statement_list until the search_condition evaluates to true Syntax:
[begin_label:] WHILE search_condition DO statement_list END WHILE [end_label]

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


For Ex:
WHILE @count < 10 DO SET @count = @count + 1; END WHILE;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


REPEAT UNTIL Statement REPEAT Statement is used to repeat the statement_list until the search_condition evaluates to true Syntax:
[begin_label:] REPEAT statement_list UNTIL search_condition END REPEAT [end_label]

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FLOW CONTROL CONSTRUCTS


For Ex:
DECLARE @count INT DEFAULT 0; increment: REPEAT SET @count = @count + 1; SELECT @count; UNTIL @count > 10 END REPEAT increment;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
Custom programming scripts with embedded SQL statements that are stored in a compiled form and executed directly by the MySQL server Allow us to store logic [rules] on the database Improves the performance as less information needs to be sent between the server and the client Procedure names can be up to 64 characters long

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
Advantages of procedures
Faster Execution: Reduced need for data transfer back and forth between a program and the database server.
Note: The use of SPs does not guarantee improved speed as a lot depends on the code inside of the SP

Reduced code redundancy: Similar code needed through out the application can be written once and can be reused. Selects, Inserts, etc.. Maintenance: If there are changes in the underlying database schema, code changes can be localized to a few SPs Security: Direct access to tables by user programs is a problem and with SPs, data access can be monitored, and logged if necessary. Centralized security rules can be applied

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
Syntax:
CREATE PROCEDURE proc_name [proc_parameter[......]]) routine_body proc_name : procedure name proc_parameter : [ IN | OUT | INOUT ] param_name type routine_body : Valid SQL procedure statement

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
If you don't specify IN, OUT, or INOUT for the parameter, it will default to IN An IN parameter is passed into the stored procedure to use internally An OUT parameter is set within the procedure, but accessed by the caller An INOUT parameter is passed into the procedure for internal use, but is also available to the caller after the procedure has completed The name and data type of the parameter are used in the stored procedure for referencing and setting values going in and out of the procedure The data type can be any valid data type for MySQL
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
For Ex: Without parameters
CREATE PROCEDURE GetStudents() BEGIN SELECT * FROM Students END

With IN Parameter
CREATE PROCEDURE GetFeesForStudent(@StudentId INT) BEGIN SELECT Fees FROM Students WHERE StudentId = @StudentId END
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
With IN and OUT parameters
CREATE PROCEDURE GetFeesForStudent(@StudentId INT, OUT @TotalFees INT) BEGIN SELECT @TotalFees := Fees FROM Students WHERE StudentId = @StudentId END

Method to invoke a procedure


CALL GetStudents(); CALL GetFeesForStudent(1001); CALL GetFeesForStudent(1001, @TotalFees);

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PROCEDURES
ALTER PROCEDURE
A procedure can be altered once created Syntax: ALTER PROCEDURE proc_name [proc_parameter[......]]) routine_body proc_name : procedure name proc_parameter : [ IN | OUT | INOUT ] param_name type routine_body : Valid SQL procedure statement

DROP PROCDURE
DROP PROCEDURE IF EXISTS procedure_name

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FUNCTIONS
Functions are also scripts with embedded SQL statements, that are stored in a compiled form and executed directly by MySQL server The main differences between a function and a procedure are
Function can return only one value and procedure can return one or more values Functions dont have different set of parameters like procedures. Parameters can only be supplied to Functions Functions may internally invoke other functions only unlike procedures which can invoke other procedures or functions

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FUNCTIONS
Syntax:
CREATE FUNCTION RETURNS type routine_body func_name ([func_parameter[,...]])

func_name : Function name func_parameter : param_name type type : Any valid MySQL datatype routine_body : Valid SQL procedure statement The RETURN clause is mandatory for FUNCTION Method to invoke a function Function_name();

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FUNCTIONS
For Ex:
CREATE FUNCTION reduce(str VARCHAR(255), len INT) RETURNS VARCHAR(255) BEGIN IF ISNULL(str) THEN RETURN NULL; END IF; IF len = 0 OR CHAR_LENGTH( str ) = 0 OR CHAR_LENGTH( str ) <= len THEN RETURN str; ELSE RETURN CONCAT( LEFT( str, len - 10 ), ' ___ ', RIGHT( str, 5 ) ); END IF; END
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FUNCTIONS
ALTER FUNCTION
ALTER FUNCTION RETURNS type routine_body func_name ([func_parameter[,...]])

func_name : Function name func_parameter : param_name type type : Any valid MySQL datatype routine_body : Valid SQL statements

DROP FUNCTION
DROP FUNCTION IF EXISTS function_name;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
A named database object which defines some action that the database should take when some databases related event occurs Are automatic execution of SQL commands or a stored procedure after or before INSERT, UPDATE, or DELETE commands

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
Syntax:
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_statement Trigger_time means trigger action time Trigger_event specifies the statement that executes the trigger Trigger_statement has the statement that executes when the trigger fires but if you want to execute multiple statements then you have to use the BEGINEND compound statement.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
For Ex: [To insert default CourseId after student insert.
CREATE TRIGGER ins_trig AFTER INSERT ON Students FOR EACH ROW BEGIN INSERT INTO StudentCourses (StudentId, CourseId) VALUES (NEW.StudentId, 1) END; INSERT INTO Students (StudentId, Name, Fees, JoinDate) VALUES (1004, Krishna Kumar S, 1000, 2010-12-05)

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
For Ex:
CREATE TRIGGER updtrigger BEFORE UPDATE ON Students FOR EACH ROW BEGIN IF NEW.Fees <= 1000 THEN SET NEW.Fees =1000; END IF; END UPDATE Students SET Fees = 500 WHERE StudentId = 1001;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRIGGERS
Note:
There cannot be two triggers at the same time for the same action on a table Up to six triggers can be defined for each table Every trigger name has to be unique OLD.column_name is used to refer the column of an existing row before it is deleted or updated NEW.column_name is used to refer the column of a new row that is inserted or after updated existing row

To delete a trigger
DROP TRIGGER updtrigger;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CURSORS
Cursors are used when the SQL Select statement is expected to return more than one row Cursors are supported inside procedures and functions Cursors must be declared and its definition contains the query A cursor must be opened before processing, data should be fetched for processing and closed after processing

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CURSORS
Syntax:
DECLARE <cursor_name> CURSOR FOR <select_statement> OPEN <cursor_name> FETCH <cursor_name> INTO <var1>,<var2> CLOSE <cursor_name>

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CURSORS
For EX:
DECLARE @StudentId, @record_not_found int DEFAULT 0; DECLARE @StudentCursor CURSOR FOR SELECT StudentId From Students DECLARE CONTINUE HANDLER FOR NOT FOUND SET @record_not_found = 1 OPEN CURSOR @StudentCursor Cursorloop: LOOP IF @record_not_found THEN
LEAVE Cursorloop;

FETCH @StudentCursor INTO @StudentId INSERT INTO StudentCourses (StudentId, CourseId) VALUES (@StudentId, 1); END LOOP Cursorloop CLOSE @StudentCursor
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Question Time
Please try to limit the questions to the topics discussed during the session. Thank you .

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Potrebbero piacerti anche