Author
gokul-sridhar
View
51
Download
0
Embed Size (px)
DESCRIPTION
Unit6 ProgrammingWithMySQL
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
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� REPEAT UNTIL
� Procedures
� Functions
� Triggers
� Cursors
VARIABLES
� You can store a value in a user-defined variable in onestatement and then refer to it later in another statement
� This enables you to pass values from one statement toanother
� User variables are written as @var_name, where the
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� User variables are written as @var_name, where thevariable name var_name consists of alphanumeric andthe special character “_”
VARIABLES
� Syntax:
� DECLARE @varname1, @varname2, ... data type [DEFAULT
value];
� For Ex:
� DECLARE @Student_Id int;
� DECLARE @Sname, @Cname varchar(15);
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� Variable assignment
� For variable assignments, use either SET or SELECT
� SET @Sname = ‘Krishna’;
� SELECT @Sname := Name FROM Students
WHERE StudentId = 1001;
VARIABLES
� For SET, either = or := can be used as the assignmentoperator.
� For statements other than SET := must be used since =is treated as a comparison operator
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
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 blockof statements using BEGIN…..END statement.
� These constructs can be nested also.
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� These constructs can be nested also.
FLOW CONTROL CONSTRUCTS
� IF Statement
� Syntax
� IF search_condition THEN
statement_list
ELSE IF search_condition THEN
statement_list
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
statement_list
ELSE
statement_list
END IF
� For Ex:
� IF @CourseId = 1 THEN
SET @Fees = 1000;
FLOW CONTROL CONSTRUCTS
� CASE Statement
� Syntax
� CASE case_value
� WHEN when_value THEN statement_list
� [WHEN when_value THEN statement_list] ... [ELSEstatement_list]
END CASE
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
END CASE
Or
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ... [ELSE statement_list]
END CASE
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
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
CASE @delivery_dayWHEN 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;
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.
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
statements.
� Loop is exited with a LEAVE Statement
FLOW CONTROL CONSTRUCTS
� Loop Syntax
[begin_label:] LOOP
statement_list
END LOOP [end_label]
� For Ex:� DECLARE @counter INT DEFAULT 0;
simple_loop: LOOP
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
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;
FLOW CONTROL CONSTRUCTS
� WHILE Statement
� The WHILE Statement repeats the statement_list until thesearch_condition evaluates to true
� Syntax:
� [begin_label:] WHILE search_condition DO
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� [begin_label:] WHILE search_condition DOstatement_list
END WHILE [end_label]
FLOW CONTROL CONSTRUCTS
� For Ex:
� WHILE @count < 10 DO
SET @count = @count + 1;
END WHILE;
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
FLOW CONTROL CONSTRUCTS
� REPEAT UNTIL Statement
� REPEAT Statement is used to repeat the statement_listuntil the search_condition evaluates to true
� Syntax:
� [begin_label:] REPEAT
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� [begin_label:] REPEATstatement_list
UNTIL search_conditionEND REPEAT [end_label]
FLOW CONTROL CONSTRUCTS
� For Ex:
� DECLARE @count INT DEFAULT 0;
increment: REPEATSET @count = @count + 1;SELECT @count;UNTIL @count > 10
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
UNTIL @count > 10END REPEAT increment;
PROCEDURES
� Custom programming scripts with embedded SQLstatements that are stored in a compiled form andexecuted directly by the MySQL server
� Allow us to store logic [rules] on the database
� Improves the performance as less information needs to
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� Improves the performance as less information needs tobe sent between the server and the client
� Procedure names can be up to 64 characters long
PROCEDURES
� Advantages of procedures
� Faster Execution: Reduced need for data transfer back and forthbetween 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 outthe application can be written once and can be reused. Selects,
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
the application can be written once and can be reused. Selects,Inserts, etc..
� Maintenance: If there are changes in the underlying databaseschema, code changes can be localized to a few SPs
� Security: Direct access to tables by user programs is a problemand with SPs, data access can be monitored, and logged ifnecessary. Centralized security rules can be applied
PROCEDURES
� Syntax:
� CREATE PROCEDURE proc_name [proc_parameter[......]]) routine_body
� proc_name : procedure nameproc_parameter : [ IN | OUT | INOUT ] param_name typeroutine_body : Valid SQL procedure statement
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
routine_body : Valid SQL procedure statement
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 touse internally
� An OUT parameter is set within the procedure, butaccessed by the caller
� An INOUT parameter is passed into the procedure for
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� An INOUT parameter is passed into the procedure forinternal use, but is also available to the caller after theprocedure has completed
� The name and data type of the parameter are used in thestored procedure for referencing and setting values goingin and out of the procedure
� The data type can be any valid data type for
MySQL
PROCEDURES
� For Ex:
� Without parameters
� CREATE PROCEDURE GetStudents()
BEGIN
SELECT * FROM Students
END
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� With IN Parameter
� CREATE PROCEDURE GetFeesForStudent(@StudentId INT)
BEGIN
SELECT Fees
FROM Students
WHERE StudentId = @StudentId
END
PROCEDURES
� With IN and OUT parameters
� CREATE PROCEDURE GetFeesForStudent(@StudentId INT,OUT @TotalFees INT)
BEGIN
SELECT @TotalFees := Fees
FROM Students
WHERE StudentId = @StudentId
END
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
END
� Method to invoke a procedure
� CALL GetStudents();
� CALL GetFeesForStudent(1001);
� CALL GetFeesForStudent(1001, @TotalFees);
PROCEDURES
� ALTER PROCEDURE
� A procedure can be altered once created
� Syntax:
� ALTER PROCEDURE proc_name [proc_parameter[......]]) routine_body
� proc_name : procedure name
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� proc_name : procedure nameproc_parameter : [ IN | OUT | INOUT ] param_name typeroutine_body : Valid SQL procedure statement
� DROP PROCDURE
� DROP PROCEDURE IF EXISTS procedure_name
FUNCTIONS
� Functions are also scripts with embedded SQLstatements, that are stored in a compiled form andexecuted directly by MySQL server
� The main differences between a function and a procedureare
� Function can return only one value and procedure can return one
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� Function can return only one value and procedure can return oneor more values
� Functions don’t have different set of parameters like procedures.Parameters can only be supplied to Functions
� Functions may internally invoke other functions only unlikeprocedures which can invoke other procedures or functions
FUNCTIONS
� Syntax:
� CREATE FUNCTION func_name ([func_parameter[,...]])RETURNS type
routine_body
� func_name : Function namefunc_parameter : param_name typetype : Any valid MySQL datatype
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
type : Any valid MySQL datatyperoutine_body : Valid SQL procedure statement
� The RETURN clause is mandatory for FUNCTION
� Method to invoke a function
� Function_name();
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(
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� 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
FUNCTIONS
� ALTER FUNCTION
� ALTER FUNCTION func_name ([func_parameter[,...]])RETURNS type
routine_body
� func_name : Function namefunc_parameter : param_name typetype : Any valid MySQL datatype
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
type : Any valid MySQL datatyperoutine_body : Valid SQL statements
� DROP FUNCTION
� DROP FUNCTION IF EXISTS function_name;
TRIGGERS
� A named database object which defines some action thatthe database should take when some databases relatedevent occurs
� Are automatic execution of SQL commands or a storedprocedure after or before INSERT, UPDATE,
or DELETE commands
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
or DELETE commands
TRIGGERS
� Syntax:
� CREATE TRIGGER trigger_name trigger_time trigger_event ONtbl_name FOR EACH ROW trigger_statement
� Trigger_time means trigger action time
� Trigger_event specifies the statement that executes the trigger
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� Trigger_statement has the statement that executes when thetrigger fires but if you want to execute multiple statements thenyou have to use the BEGIN…END compound statement.
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;
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� INSERT INTO Students (StudentId, Name, Fees, JoinDate)
VALUES (1004, ‘Krishna Kumar S’, 1000, ‘2010-12-05’)
TRIGGERS
� For Ex:
� CREATE TRIGGER updtrigger BEFORE UPDATE ON Students FOR EACH ROW
BEGIN
IF NEW.Fees <= 1000 THEN
SET NEW.Fees =1000;
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
END IF;
END
� UPDATE Students SET Fees = 500 WHERE StudentId = 1001;
TRIGGERS
� Note:
� There cannot be two triggers at the same time for the same actionon 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 rowbefore it is deleted or updated
� NEW.column_name is used to refer the column of a new row that
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� NEW.column_name is used to refer the column of a new row thatis inserted or after updated existing row
� To delete a trigger
� DROP TRIGGER updtrigger;
CURSORS
� Cursors are used when the SQL Select statement isexpected to return more than one row
� Cursors are supported inside procedures and functions
� Cursors must be declared and its definition contains thequery
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
query
� A cursor must be opened before processing, data shouldbe fetched for processing and closed after processing
CURSORS
� Syntax:
� DECLARE <cursor_name> CURSOR FOR <select_statement>
� OPEN <cursor_name>
� FETCH <cursor_name> INTO <var1>,<var2>……
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� FETCH <cursor_name> INTO <var1>,<var2>……
� CLOSE <cursor_name>
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
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com
� 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
Please try to limit the questions to the topics discussed during the session. Thank you
.
Question Time
Basic SQLCopyright © 2010 Pratian Technologies
www.pratian.com