3. 3
SQL (User) Variable
MySQL allows you to assign values to variables and refer to them later.
This is useful when you want to save the results of calculations for use in subsequent
statements.
If you refer to an uninitialized variable that has not been assigned a value explicitly, its
value is NULL.
User variables are specific to the client connection within which they are used and exist
only for the duration of that connection.
A user variable used within a connection cannot be accessed by other connections. When
a connection ends, all its user variables are lost.
SET @var1:="USA", @var2="GBR", @var3="CAN";
SELECT @var1, @var2, @var3, @var4;
Table Variable (Temporary table)
It’s visible only to the client that created it and may be used only by that client. This means
that different clients can create TEMPORARY tables that have the same name and no
conflict occurs.
A TEMPORARY table exists only for the duration of the connection in which it was created.
A TEMPORARY table may have the same name as a non-TEMPORARY table.
A TEMPORARY table can be renamed only with ALTER TABLE. You cannot use RENAME
TABLE.
CREATE TEMPORARY TABLE tmp_table
SELECT CountryCode, COUNT(*) AS LangCount FROM CountryLanguage GROUP BY CountryCode;
DROP TABLE tmp_table;
4. 4
Iteration
Compound statement syntax in MySQL provides for three kinds of loops.
LOOP constructs an unconditional loop with no loop-termination syntax. For this reason, it must contain a
statement that explicitly exits the loop.
LOOP
statement_list
END LOOP
DECLARE i INT DEFAULT 0;
my_loop: LOOP
SET i = i + 1;
IF i >= 10 THEN
LEAVE my_loop;
END IF;
END LOOP my_loop;
REPEAT and WHILE, the other two loop constructs, are conditional. They include a clause that determines
whether loop execution continues or terminates.
REPEAT
statement_list UNTIL expr
END REPEAT
DECLARE i INT DEFAULT 0;
REPEAT
SET i = i + 1;
UNTIL i >= 10
END REPEAT;
WHILE expr DO
statement_list
END WHILE
WHILE 1 = 0 DO
SET x = 1;
END WHILE;
5. 5
Control Flow Functions [Case/Condition]
Control flow functions enable you to choose between different values based on the result of
an expression.
IF() tests the expression in its first argument and returns its second or third argument
depending on whether the expression is true or false:
SELECT IF(1 > 0, ‘yes’,’no’);
IF val IS NULL
THEN SELECT ‘val is NULL’;
ELSE SELECT ‘val is not NULL’;
END IF;
The CASE construct is not a function, but it too provides flow control. It has two forms of
syntax.
mysql> SET @val = 1;
mysql> SELECT CASE @val
-> WHEN 0 THEN ‘@val is 0’
-> WHEN 1 THEN ‘@val is 1’
-> ELSE ‘@valisnot0or1’ -> END AS result;
mysql> SET @val = NULL;
mysql> SELECT CASE
-> WHEN @val IS NULL THEN ‘@val is NULL’
-> WHEN @val < 0 THEN ‘@val is less than 0’
-> WHEN @val > 0 THEN ‘@val is greater than 0’
-> ELSE ‘@val is 0’
-> END AS result;
6. 6
Cursor
A cursor enables you to access a result set one row at a time.
Because of this row orientation, cursors often are used in loops that fetch and process a row within each
iteration of the loop.
Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor
points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive
cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of
data.
Read only: Not updatable, You can not write cursor like declare curs1 cursor for Update test111 set id=2.
Nonscrollable: Can be traversed only in one direction and cannot skip rows.
BEGIN DECLARE row_count INT DEFAULT 0;
DECLARE code_var CHAR(3);
DECLARE name_var CHAR(52);
DECLARE c CURSOR FOR
SELECT Code, Name FROM Country WHERE Continent = ‘Africa’;
OPEN c;
BEGIN
DECLARE EXIT HANDLER FOR SQLSTATE ‘02000’ BEGIN END;
LOOP
FETCH c INTO code_var, name_var;
SET row_count = row_count + 1;
END LOOP;
END;
CLOSE c;
SELECT ‘number of rows fetched =’, row_count;
END;
7. 7
Cursor
Advantages:
No need to write business logic after fetching data from your code logic.
Gives you better flexibility for operating even on the single column of the row. Manipulation
become always easy.
Saves you from the simplex join structure.
Easy to maintain the business logic of your application at one place.
Disadvantages:
Slow down your stored procedure or function performance in cause of large record set in
cursor.
Debugging of your business logic become tough.
Hard to manage.
Need to consider locking of the database.
8. 8
Trigger
A trigger is an object that belongs to a database.
Each trigger within the database must have a different name.
A trigger is defined to activate when a particular kind of event occurs for a given table.
The trigger definition includes a statement to be executed when the trigger activates.
The events for which triggers can be defined are INSERT, DELETE, and UPDATE.
A given trigger is defined for only one of these events, but you can define multiple triggers
for a table, one trigger per type of event.
Triggers can be defined to activate either before or after the event. This means there can
be two triggers per event (for example, one trigger to activate before an UPDATE and one
to activate after).
A trigger can change values before they are inserted into a table or used to update a table.
For example, you can check for out-of-bounds values and modify them to be within bounds.
This capability enables the use of triggers as data filters.
You cannot create a trigger for a TEMPORARY table or a view.
CREATE TRIGGER trigger_name
{ BEFORE | AFTER }
{ INSERT | UPDATE | DELETE } ON table_name
FOR EACH ROW triggered_statement
CREATE TRIGGER Capital_bi
BEFORE INSERT
ON Capital
FOR EACH ROW
SET NEW.Population = IF(NEW.Population < 0, 0, TRUNCATE(NEW.Population,-3));
mysql> INSERT INTO Capital VALUES -> (‘CountryA’,’CityA’,-39),
-> (‘CountryB’,’CityB’,123456);
9. 9
VIEW
View is a DB object which is defined in terms of a SELECT statement that retrieves the
data you want the view to produce.
Views are sometimes called “virtual tables”.
A view can be used to select from regular tables (called “base tables”) or other views.
Creating Views : To create a view.
CREATE VIEW CityView AS SELECT ID, Name FROM City;
CREATE VIEW CountryLangCount (Name, LangCount) AS
-> SELECT Name, COUNT(Language)
-> FROM Country, CountryLanguage WHERE Code = CountryCode -> GROUP BY Name;
Altering Views : To change the definition of an existing view.
ALTER VIEW LargePop AS SELECT Name, Population FROM CountryPop WHERE Population >= 100000000;
Dropping Views :
DROP VIEW IF EXISTS v1, v2;
Advantages:
Access to data becomes simplified because it contains subset of data from multiple tables.
Views can be used to display table contents differently for different users, so that each user
sees only the data pertaining to that user’s activities.
Join and simplify multiple tables into a single virtual table.
Acts as aggregated tables, where aggregated data (sum, average etc.) are calculated and
presented as part of the data.
Gives real time data.
10. 10
VIEW
Disadvantages:
When table is dropped view becomes inactive, it depends on the table objects.
It affects performance, querying from view takes more time than directly querying from the
table
Restrictions on Views:
You cannot create a TEMPORARY view.
You cannot associate a trigger with a view.
The tables on which a view is to be based must already exist.
The SELECT statement in a view definition cannot contain any of these constructs:
Subqueries in the FROM clause
References to TEMPORARY tables
References to user variables
References to procedure parameters, if the view definition occurs within a stored routine
References to prepared statement parameters
11. 11
Benefits of Stored Routines (Procedure & Function)
More flexible SQL syntax : Stored routines can be written using compound statements and
flow-control constructs, that make it easier to express complex logic.
Error handling capabilities (Stored Procedure)
Standards compliance.
Code packaging and encapsulation, A routine allows the code that performs an operation to
be stored once on the server and accessed from multiple applications.
Less “re-invention of the wheel.” A collection of stored routines acts as a library of solutions
to problems.
Separation of logic.
Ease of maintenance.
Reduction in network bandwidth requirements.
Better security.
Namespace for Stored Routines
MySQL interprets an unqualified reference, routine_name, as a reference to a procedure or
function in the default database. To refer to a routine in a specific database, use a qualified
name of the form db_name.routine_name.
Due to this association of a routine with a database, you must have access to that database
to be able to invoke the routine.
When you drop a database, any stored routines in the database are also dropped.
12. 12
Stored Procedure
Creating Stored Procedures:
CREATE PROCEDURE proc_name ([parameters]) [characteristics]
routine_body
CREATE PROCEDURE rect_area (width INT, height INT)
SELECT width * height AS area;
Stored Procedure with Compound Statements (Begins and ends with the BEGIN and END keywords and
creates a block).
mysql> delimiter //
mysql> CREATE PROCEDURE world_record_count ()
-> BEGIN
-> SELECT ‘Country’, COUNT(*) FROM Country;
-> SELECT ‘City’, COUNT(*) FROM City;
-> SELECT ‘CountryLanguage’, COUNT(*) FROM CountryLanguage;
-> END;
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
Declaring Parameters:
IN indicates an input parameter. The parameter value is passed in from the caller to the
procedure
OUT indicates an output parameter. The procedure sets its value, and after the proce- dure
terminates. The caller sees that value when it accesses the variable.
INOUT indicates a “two-way” parameter that can be used both for input and for output.
If no keyword is given before a procedure parameter name, it is an IN parameter by default.
13. 13
Stored Procedure
Stored Procedure with Declared Parameters
CREATE PROCEDURE param_test (IN p_in INT, OUT p_out INT, INOUT p_inout INT)
BEGIN SELECT p_in, p_out, p_inout;
SET p_in = 100, p_out = 200, p_inout = 300;
END;
SET @v_in = 0, @v_out = 0, @v_inout = 0;
Calling(Invoking) Stored Procedure
CALL param_test(@v_in, @v_out, @v_inout);
The DECLARE Statement in Stored Procedure:
Local variables
Conditions, such as warnings or exceptions
Handlers for conditions
Cursors for accessing result sets row by row
Variables in Stored Procedure:
DECLARE var_name [, var_name] ... data_type [DEFAULT value]
Assigning Variable Values with SET:
DECLARE var1, var2, var3 INT;
SET var1 = 1, var2 = 2;
SET var3 = var1 + var2;
Variables in Stored Procedure:
DECLARE name_var CHAR(52);
DECLARE pop_var INT;
SELECT Name, Population INTO name_var, pop_var
FROM Country WHERE Code = ‘ESP’;
14. 14
Function
Creating Function:
CREATE FUNCTION func_name ([parameters])
RETURNS data_type
[characteristics]
routine_body
CREATE FUNCTION circle_area (radius FLOAT)
RETURNS FLOAT
RETURN PI() * radius * radius;
Calling(Invoking) Function
SELECT circle_area(10);
Functions can have Compound Statements, Declared Parameters & Variables as Store Procedure has.
15. 15
Difference Between Stored Procedure and Function
Function is not pre-compiled object it will execute every time whenever it was called.
Function must return a value but in Stored Procedure it is optional (Procedure can return
zero or n values).
Functions can have only input parameters for it whereas Procedures can have input/output
parameters .
Function takes one input parameter it is mandatory but Stored Procedure may take o to n
input parameters.
Functions can be called from Procedure whereas Procedures cannot be called from
Function.
Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it
whereas Function allows only SELECT statement in it.
Procedures can not be utilized in a SELECT statement whereas Function can be
embedded in a SELECT statement.
Stored Procedures cannot be used in the SQL statements anywhere in the
WHERE/HAVING/SELECT section whereas Function can be.
Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot
be used in a Function.
We can go for Transaction Management in Procedure whereas we can't go in Function.
http://tutoriz.com/Thread-Difference-between-Stored-Procedure-and-Function-in-Sql-with-Example