Unit6 ProgrammingWithMySQL

of 35/35
Unit 6: Programming with MySQL Pratian Technologies (India) Pvt. Ltd. www.pratian.com
  • date post

    01-Jan-2016
  • Category

    Documents

  • view

    36
  • download

    0

Embed Size (px)

description

Unit6 ProgrammingWithMySQL

Transcript of 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 Technologieswww.pratian.com

    REPEAT UNTIL Procedures Functions Triggers Cursors

  • 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 toanother

    User variables are written as @var_name, where the

    Basic SQLCopyright 2010 Pratian Technologieswww.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 [DEFAULTvalue];

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

    Basic SQLCopyright 2010 Pratian Technologieswww.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 assignment

    operator.

    For statements other than SET := must be used since =is treated as a comparison operator

    Basic SQLCopyright 2010 Pratian Technologieswww.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 Technologieswww.pratian.com

    These constructs can be nested also.

  • FLOW CONTROL CONSTRUCTS IF Statement

    Syntax

    IF search_condition THENstatement_list

    ELSE IF search_condition THENstatement_list

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    statement_listELSE

    statement_listEND 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] ... [ELSE

    statement_list]END CASE

    Basic SQLCopyright 2010 Pratian Technologieswww.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 Technologieswww.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 onestatements.

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    statements.

    Loop is exited with a LEAVE Statement

  • FLOW CONTROL CONSTRUCTS Loop Syntax

    [begin_label:] LOOPstatement_list

    END LOOP [end_label]

    For Ex: DECLARE @counter INT DEFAULT 0;

    simple_loop: LOOP

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    simple_loop: LOOPSET @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 Technologieswww.pratian.com

    [begin_label:] WHILE search_condition DOstatement_list

    END WHILE [end_label]

  • FLOW CONTROL CONSTRUCTS For Ex:

    WHILE @count < 10 DOSET @count = @count + 1;

    END WHILE;

    Basic SQLCopyright 2010 Pratian Technologieswww.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 Technologieswww.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 Technologieswww.pratian.com

    UNTIL @count > 10END REPEAT increment;

  • PROCEDURES Custom programming scripts with embedded SQL

    statements 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 Technologieswww.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 out

    the application can be written once and can be reused. Selects,

    Basic SQLCopyright 2010 Pratian Technologieswww.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 Technologieswww.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 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

    Basic SQLCopyright 2010 Pratian Technologieswww.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 forMySQL

  • PROCEDURES For Ex: Without parameters

    CREATE PROCEDURE GetStudents()BEGIN

    SELECT * FROM StudentsEND

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    With IN Parameter CREATE PROCEDURE GetFeesForStudent(@StudentId INT)

    BEGINSELECT FeesFROM StudentsWHERE StudentId = @StudentId

    END

  • PROCEDURES With IN and OUT parameters

    CREATE PROCEDURE GetFeesForStudent(@StudentId INT,OUT @TotalFees INT)BEGIN

    SELECT @TotalFees := FeesFROM StudentsWHERE StudentId = @StudentId

    END

    Basic SQLCopyright 2010 Pratian Technologieswww.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 Technologieswww.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 SQL

    statements, 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 Technologieswww.pratian.com

    Function can return only one value and procedure can return oneor 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 unlikeprocedures which can invoke other procedures or functions

  • FUNCTIONS Syntax:

    CREATE FUNCTION func_name ([func_parameter[,...]])RETURNS typeroutine_body

    func_name : Function namefunc_parameter : param_name typetype : Any valid MySQL datatype

    Basic SQLCopyright 2010 Pratian Technologieswww.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 Technologieswww.pratian.com

    IF len = 0 OR CHAR_LENGTH( str ) = 0 OR CHAR_LENGTH(str )

  • FUNCTIONS ALTER FUNCTION

    ALTER FUNCTION func_name ([func_parameter[,...]])RETURNS typeroutine_body

    func_name : Function namefunc_parameter : param_name typetype : Any valid MySQL datatype

    Basic SQLCopyright 2010 Pratian Technologieswww.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 that

    the 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 Technologieswww.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 Technologieswww.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 BEGINEND compound statement.

  • TRIGGERS For Ex: [To insert default CourseId after student insert.

    CREATE TRIGGER ins_trig AFTER INSERT ON StudentsFOR EACH ROWBEGIN

    INSERT INTO StudentCourses (StudentId, CourseId) VALUES(NEW.StudentId, 1)END;

    Basic SQLCopyright 2010 Pratian Technologieswww.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 ROWBEGIN

    IF NEW.Fees

  • 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 row

    before it is deleted or updated NEW.column_name is used to refer the column of a new row that

    Basic SQLCopyright 2010 Pratian Technologieswww.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 is

    expected 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 Technologieswww.pratian.com

    query

    A cursor must be opened before processing, data shouldbe fetched for processing and closed after processing

  • CURSORS Syntax:

    DECLARE CURSOR FOR

    OPEN

    FETCH INTO ,

    Basic SQLCopyright 2010 Pratian Technologieswww.pratian.com

    FETCH INTO ,

    CLOSE

  • 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 Technologieswww.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 Technologieswww.pratian.com