Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Overview
Variables Flow control constructs
IF THEN ELSE CASE LOOP WHILE REPEAT UNTIL
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 _
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;
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
Basic SQL
Basic SQL
For Ex:
IF @CourseId = 1 THEN SET @Fees = 1000;
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
...
[ELSE
Basic SQL
Basic SQL
Basic SQL
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;
Basic SQL
Basic SQL
Basic SQL
Basic SQL
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
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
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
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
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
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
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();
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;
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
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.
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)
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;
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;
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
Basic SQL
CURSORS
Syntax:
DECLARE <cursor_name> CURSOR FOR <select_statement> OPEN <cursor_name> FETCH <cursor_name> INTO <var1>,<var2> CLOSE <cursor_name>
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 .
Basic SQL