Você está na página 1de 24

Using stored procedures requires knowing how to execute (run) them.

Stored procedures are executed far more often than they are written, so we'll start there. And then we'll look at creating and working with stored procedures. Executing Stored Procedures MySQL refers to stored procedure execution as calling, and so the MySQL statement to execute a stored procedure is simply CALL. CALL takes the name of the stored procedure and any parameters that need to be passed to it. Take a look at this example: Input
CALL productpricing(@pricelow, @pricehigh, @priceaverage);

Analysis Here a stored procedure named productpricing is executed; it calculates and returns the lowest, highest, and average product prices. Stored procedures might or might not display results, as you will see shortly. Creating Stored Procedures As already explained, writing a stored procedure is not trivial. To give you a taste for what is involved, let's look at a simple examplea stored procedure that returns the average product price. Here is the code: Input
CREATE PROCEDURE productpricing() BEGIN SELECT Avg(prod_price) AS priceaverage FROM products; END;

Analysis Ignore the first and last lines for a moment; we'll come back to them shortly. The stored procedure is named productpricing and is thus defined with the statement CREATE PROCEDURE productpricing(). Had the stored procedure accepted parameters, these would have been enumerated between the ( and ). This stored procedure has no parameters, but the trailing () is still required. BEGIN and END statements are used to delimit the stored procedure body, and the body itself is just a simple SELECT statement (using the Avg() function learned in Tutorial 12, "Summarizing Data"). When MySQL processes this code it creates a new stored procedure named productpricing. No data is returned because the code does not call the stored procedure, it simply creates it for future use. Note mysql Command-line Client Delimiters If you are using the mysql command-line utility, pay careful attention to this note. The default MySQL statement delimiter is ; (as you have seen in all of the MySQL statement used thus far). However, the mysql command-line utility also uses ; as a delimiter. If the command-line utility were to interpret the ; characters inside of the stored procedure itself, those would not end up becoming part of the stored procedure, and that would make the SQL in the stored procedure syntactically invalid. The solution is to temporarily change the command-line utility delimiter, as seen here:
DELIMITER // CREATE PROCEDURE productpricing() BEGIN SELECT Avg(prod_price) AS priceaverage FROM products; END // DELIMITER ;

Here, DELIMITER // tells the command-line utility to use // as the new end of statement delimiter, and you will notice that the END that closes the stored procedure is defined as END // instead of the expected END;. This way the ; within the stored procedure body remains intact and is correctly passed to the database engine. And then, to restore things back to how they were initially, the statement closes with a DELIMITER ;. Any character may be used as the delimiter except for \. If you are using the mysql command-line utility, keep this in mind as you work through this tutorial. So how would you use this stored procedure? Like this: Input
CALL productpricing();

Output
+--------------+ | priceaverage | +--------------+ | 16.133571 | +--------------+

Analysis CALL productpricing(); executes the just-created stored procedure and displays the returned result. As a stored procedure is actually a type of function, () characters are required after the stored procedure name (even when no parameters are being passed). Dropping Stored Procedures After they are created, stored procedures remain on the server, ready for use, until dropped. The drop command (similar to the statement seen Tutorial 21, "Creating and Manipulating Tables") removes the stored procedure from the server. To remove the stored procedure we just created, use the following statement: Input
DROP PROCEDURE productpricing;

Analysis This removes the just-created stored procedure. Notice that the trailing () is not used; here just the stored procedure name is specified. Tip Drop Only If It Exists DROP PROCEDURE will throw an error if the named procedure does not actually exist. To delete a procedure if it exists (and not throw an error if it does not), use DROP PROCEDURE IF EXISTS.

Working with Parameters productpricing is a really simple stored procedureit simply displays the results of a SELECT statement. Typically stored procedures do not display results; rather, they return them into variables that you specify. New Term Variable A named location in memory, used for temporary storage of data. Here is an updated version of productpricing (you'll not be able to create the stored procedure again if you did not previously drop it): Input

CREATE PROCEDURE productpricing( OUT pl DECIMAL(8,2), OUT ph DECIMAL(8,2), OUT pa DECIMAL(8,2) ) BEGIN SELECT Min(prod_price) INTO pl FROM products; SELECT Max(prod_price) INTO ph FROM products; SELECT Avg(prod_price) INTO pa FROM products; END;

Analysis This stored procedure accepts three parameters: pl to store the lowest product price, ph to store the highest product price, and pa to store the average product price (and thus the variable names). Each parameter must have its type specified; here a decimal value is used. The keyword OUT is used to specify that this parameter is used to send a value out of the stored procedure (back to the caller). MySQL supports parameters of types IN (those passed to stored procedures), OUT (those passed from stored procedures, as we've used here), and INOUT (those used to pass parameters to and from stored procedures). The stored procedure code itself is enclosed within BEGIN and END statements as seen before, and a series of SELECT statements are performed to retrieve the values that are then saved into the appropriate variables (by specifying the INTO keyword). Note Parameter Datatypes The datatypes allowed in stored procedure parameters are the same as those used in tables. Appendix D, "MySQL Datatypes," lists these types. Note that a recordset is not an allowed type, and so multiple rows and columns could not be returned via a parameter. This is why three parameters (and three SELECT statements) are used in the previous example. To call this updated stored procedure, three variable names must be specified, as seen here: Input
CALL productpricing(@pricelow, @pricehigh, @priceaverage);

Analysis As the stored procedure expects three parameters, exactly three parameters must be passed, no more and no less. Therefore, three parameters are passed to this CALL statement. These are the names of the three variables that the stored procedure will store the results in.

Note Variable Names All MySQL variable names must begin with @. When called, this statement does not actually display any data. Rather, it returns variables that can then be displayed (or used in other processing). To display the retrieved average product price you could do the following: Input
SELECT @priceaverage;

Output
+---------------+ | @priceaverage | +---------------+ | 16.133571428 | +---------------+

To obtain all three values, you can use the following: Input
SELECT @pricehigh, @pricelow, @priceaverage;

Output
+------------+-----------+---------------+ | @pricehigh | @pricelow | @priceaverage | +------------+-----------+---------------+ | 55.00 | 2.50 | 16.133571428 | +------------+-----------+---------------+

Here is another example, this time using both IN and OUT parameters. ordertotal accepts an order number and returns the total for that order: Input
CREATE PROCEDURE ordertotal( IN onumber INT, OUT ototal DECIMAL(8,2) ) BEGIN SELECT Sum(item_price*quantity) FROM orderitems WHERE order_num = onumber INTO ototal; END;

Analysis onumber is defined as IN because the order number is passed in to the stored procedure. ototal is defined as OUT because the total is to be returned from the stored procedure. The SELECT statement used both of these parameters, the WHERE clause uses onumber to select the right rows, and INTO uses ototal to store the calculated total. To invoke this new stored procedure you can use the following: Input
CALL ordertotal(20005, @total);

Analysis Two parameters must be passed to ordertotal; the first is the order number and the second is the name of the variable that will contain the calculated total. To display the total you can then do the following: Input
SELECT @total;

Output
+--------+ | @total | +--------+ | 149.87 | +--------+

Analysis @total has already been populated by the CALL statement to ordertotal, and SELECT displays the value it contains. To obtain a display for the total of another order, you would need to call the stored procedure again, and then redisplay the variable: Input
CALL ordertotal(20009, @total); SELECT @total;

Building Intelligent Stored Procedures All of the stored procedures used thus far have basically encapsulated simple MySQL SELECT statements. And while they are all valid examples of stored procedures, they really don't do anything more than what you could do with those statements directly (if anything, they just make things a little

more complex). The real power of stored procedures is realized when business rules and intelligent processing are included within them. Consider this scenario. You need to obtain order totals as before, but also need to add sales tax to the total, but only for some customers (perhaps the ones in your own state). Now you need to do several things: Obtain the total (as before). Conditionally add tax to the total. Return the total (with or without tax). That's a perfect job for a stored procedure: Input
-- Name: ordertotal -- Parameters: onumber = order number -taxable = 0 if not taxable, 1 if taxable -ototal = order total variable CREATE PROCEDURE ordertotal( IN onumber INT, IN taxable BOOLEAN, OUT ototal DECIMAL(8,2) ) COMMENT 'Obtain order total, optionally adding tax' BEGIN -- Declare variable for total DECLARE total DECIMAL(8,2); -- Declare tax percentage DECLARE taxrate INT DEFAULT 6; -- Get the order total SELECT Sum(item_price*quantity) FROM orderitems WHERE order_num = onumber INTO total; -- Is this taxable? IF taxable THEN -- Yes, so add taxrate to the total SELECT total+(total/100*taxrate) INTO total; END IF; -- And finally, save to out variable SELECT total INTO ototal; END;

Analysis The stored procedure has changed dramatically. First of all, comments have been added throughout (preceded by --). This is extremely important as stored procedures increase in complexity. An additional parameter has been addedtaxable is a BOOLEAN (specify true if taxable, false if not). Within the stored procedure body, two local variables are defined using DECLARE statements.

DECLARE requires that a variable name and datatype be specified, and also supports optional default values (taxrate in this example is set to 6%). The SELECT has changed so the result is stored in total (the local variable) instead of ototal. Then an IF statement checks to see if taxable is true, and if it is, another SELECT statement is used to add the tax to local variable total. And finally, total (which might or might not have had tax added) is saved to ototal using another SELECT statement. Tip The COMMENT Keyword The stored procedure for this example included a COMMENT value in the CREATE PROCEDURE statement. This is not required, but if specified, is displayed in SHOW PROCEDURE STATUS results. This is obviously a more sophisticated and powerful stored procedure. To try it out, use the following two statements: Input
CALL ordertotal(20005, 0, @total); SELECT @total;

Output
+--------+ | @total | +--------+ | 149.87 | +--------+

Input
CALL ordertotal(20005, 1, @total); SELECT @total;

Output
+---------------+ | @total | +---------------+ | 158.862200000 | +---------------+

Analysis BOOLEAN values may be specified as 1 for true and 0 for false (actually, any non-zero value is considered true and only 0 is considered false). By specifying 0 or 1 in the middle parameter you can conditionally add tax to the order total. Note

The IF Statement This example showed the basic use of the MySQL IF statement. IF also supports ELSEIF and ELSE clauses (the former also uses a THEN clause, the latter does not). We'll be seeing additional uses of IF (as well as other flow control statements) in future tutorials.

Inspecting Stored Procedures To display the CREATE statement used to create a stored procedure, use the SHOW CREATE PROCEDURE statement: Input
SHOW CREATE PROCEDURE ordertotal;

To obtain a list of stored procedures including details on when and who created them, use SHOW PROCEDURE STATUS. Note Limiting Procedure Status Results SHOW PROCEDURE STATUS lists all stored procedures. To restrict the output you can use LIKE to specify a filter pattern, for example:
SHOW PROCEDURE STATUS LIKE 'ordertotal';

Stored Procedures and Functions


Stored Routines (Procedures and Functions) are supported in version MySQL 5.0. Stored Procedure is a set of statements, which allow ease and flexibility for a programmer because stored procedure is easy to execute than reissuing the number of individual SQL statements. Stored procedure can call another stored procedure also. Stored Procedure can very useful where multiple client applications are written in different languages or it can be work on different platforms but they need to perform the same database operations. Store procedure can improve the performance because by using the stored procedure less information needs to be sent between the server and the client. It increase the load on the database server because less work is done on the client side and much work is done on the server side.

CREATE PROCEDURE Syntax


The general syntax of Creating a Stored Procedure is : 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

The parameter list is available with in the parentheses. Parameter can be declared to use any valid data type, except that the COLLATE attribute cannot be used. By default each parameter is an IN parameter. For specifying other type of parameter used the OUT or INOUT keyword before the parameter name. An IN parameter is used to pass the value into a procedure. The procedure can be change the value but when the procedure return the value then modification is not visible to the caller. An OUT parameter is used to pass the value from the procedure to the caller but its visible to the caller. An INOUT parameter is initialized by the caller and it can be modified by the procedure, and any change made by the procedure is visible to the caller. For each OUT or INOUT parameter you have to pass a user defined variable because then the procedure returns the value then only you can obtain it values. But if you invoking the procedure from the other procedure then you can also pass a routine parameter or variable as an IN or INOUT parameter. The routine_body contains the valid SQL procedure statement that can be a simple statement like SELECT or INSERT or they can be a compound statement written using BEGIN and END. Compound statement can consists declarations, loops or other control structure. Now we are describing you a example of a simple stored procedure which uses an OUT parameter. It uses the mysql client delimiter command for changing the statement delimiter from ; to // till the procedure is being defined. Example :
mysql> delimiter // mysql> CREATE PROCEDURE Sproc(OUT p1 INT) -> SELECT COUNT(*) INTO p1 FROM Emp; -> // Query OK, 0 rows affected (0.21 sec) mysql> delimiter ; mysql> CALL Sproc(@a); Query OK, 0 rows affected (0.12 sec) mysql> select @a; +------+ | @a | +------+ | 5 | +------+ 1 row in set (0.00 sec)

CREATE FUNCTION Syntax


The general syntax of Creating a Function is : CREATE FUNCTION func_name ([func_parameter[,...]]) RETURNS type routine_body 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. It used to indicate the return type of function. Now we are describing you a simple example a function. This function take a parameter and it is used to perform an operation by using an SQL function and return the result. In this example there is no need to use delimiter because it contains no internal ; statement delimiters. Example :

mysql> CREATE FUNCTION func(str CHAR(20)) -> RETURNS CHAR(50) -> RETURN CONCAT('WELCOME TO, ',str,'!'); Query OK, 0 rows affected (0.00 sec) mysql> SELECT func('RoseIndia'); +------------------------+ | func('RoseIndia') | +------------------------+ | WELCOME TO, RoseIndia! | +------------------------+ 1 row in set (0.00 sec)

ALTER PROCEDURE and ALTER FUNCTION Syntax


For creating the procedure or function we used the CREATE PROCEDURE | FUNCTION statement and for altering the procedure we used the ALTER PROCEDURE | FUNCTION statement. Alter Procedure statement is used to change access permissions that preserves by the procedure. And ALTER PROCEDURE needs the use of the same encryption and recompile option as the original CREATE PROCEDURE command. ALTER PROCEDURE | FUNCTION statement can be used for renaming the stored procedure or function and for changing it characteristics also. We can specify the more than one changes also in an ALTER PROCEDURE | FUNCTION statement. But for this you required the ALTER ROUTINE privilege. ALTER {PROCEDURE | FUNCTION} {proc_name | func_name} [characteristic ...] characteristic: SQL SECURITY {DEFINER | INVOKER}| COMMENT 'string' Example :
mysql> ALTER PROCEDURE Sproc SQL SECURITY DEFINER; Query OK, 0 rows affected (2.00 sec)

With the ALTER PROCEDURE Statement you can change only the characteristics and if you want to change in statement list then you have to DROP the procedure and CREATE again.

DROP PROCEDURE and DROP FUNCTION Syntax


DROP PROCEDURE | FUNCTION Statement is used to drop a Procedure or Function. But for dropping them you must have the ALTER ROUTINE privilege. If IF NOT EXISTS clause is available then its prevents you from occurring an error when the procedure or function does not exist its produced only a warning. DROP {PROCEDURE | FUNCTION} [IF EXISTS] {proc_name | func_name}; The following example shows you a syntax of Dropping procedure and function if it exists : Examples :
mysql> DROP FUNCTION IF EXISTS func; Query OK, 0 rows affected (0.30 sec) mysql> DROP PROCEDURE IF EXISTS Sproc; Query OK, 0 rows affected (0.00 sec)

But when you want to drop the procedure and function that does not exists it shows you only a warning. Examples :

mysql> DROP FUNCTION IF EXISTS func; Query OK, 0 rows affected, 1 warning (0.02 sec) mysql> DROP PROCEDURE IF EXISTS Sproc; Query OK, 0 rows affected, 1 warning (0.00 sec)

CALL Statement Syntax


The CALL statement is used to call a procedure, which has been defined previously. CALL can return the values to its caller through its parameters that are declared as OUT or INOUT parameters. This statement is also used to returns the number of rows affected that a client program can obtain at the SQL level by calling the ROW_COUNT(). The general syntax of CALL Statement is : CALL p_name([parameter[,...]]) The following example shows you the use of CALL statement. Example :
mysql> delimiter // mysql> CREATE PROCEDURE Sp1(OUT p VARCHAR(20),OUT p1 VARCHAR(20),IN p2 INT) -> SELECT Ename,City INTO p,p1 FROM Emp WHERE Eid=p2; -> // Query OK, 0 rows affected (0.02 sec) mysql> delimiter ; mysql> CALL Sp1(@Name,@City,1); Query OK, 0 rows affected (0.00 sec) mysql> SELECT @Name,@City; +-------+-------+ | @Name | @City | +-------+-------+ | Rahul | Delhi | +-------+-------+ 1 row in set (0.00 sec)

BEGIN.....END Compound Statement Syntax


Stored Procedure or Functions can contain multiple statement by using the BEGIN..END compound statement. The general syntax of BEGIN....END compound statement is : BEGIN [statement_list] END statement_list means a list of one or more statements but each statements must be terminated by a semicolon. statement_list is optional means compound statement can be empty. In the following example firstly we are inserting the record and then we are selecting the record. Example :
mysql> SELECT * FROM Emp; +-----+---------+----------+-------------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks | +-----+---------+----------+-------------------+--------+-------+ | 1 | Rahul | Delhi | Manager | 10300 | 853 | | 2 | Gaurav | Mumbai | Assistant Manager | 10300 | 853 | | 3 | Chandan | Banglore | Team Leader | 15450 | 999 | | 5 | Tapan | Pune | Developer | 20600 | 1111 | | 6 | Amar | Chennai | Developer | 16000 | 1124 | | 7 | Santosh | Delhi | Designer | 10000 | 865 |

+-----+---------+----------+-------------------+--------+-------+ 6 rows in set (0.00 sec) mysql> delimiter // mysql> CREATE PROCEDURE Proc(OUT p VARCHAR(20), OUT p1 VARCHAR(20),IN p2 INT) -> BEGIN -> INSERT INTO Emp VALUES(p2,'Suman','Pune','Web Designer',20000,965); -> SELECT Ename,City INTO p,p1 FROM Emp WHERE Eid=p2; -> END -> // Query OK, 0 rows affected (0.01 sec) mysql> delimiter ; mysql> CALL Proc(@Name,@City,8); Query OK, 0 rows affected (0.03 sec) mysql> SELECT @Name,@City; +-------+-------+ | @Name | @City | +-------+-------+ | Suman | Pune | +-------+-------+ 1 row in set (0.00 sec) mysql> SELECT * FROM Emp; +-----+---------+----------+-------------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks | +-----+---------+----------+-------------------+--------+-------+ | 1 | Rahul | Delhi | Manager | 10300 | 853 | | 2 | Gaurav | Mumbai | Assistant Manager | 10300 | 853 | | 3 | Chandan | Banglore | Team Leader | 15450 | 999 | | 5 | Tapan | Pune | Developer | 20600 | 1111 | | 6 | Amar | Chennai | Developer | 16000 | 1124 | | 7 | Santosh | Delhi | Designer | 10000 | 865 | | 8 | Suman | Pune | Web Designer | 20000 | 965 | +-----+---------+----------+-------------------+--------+-------+ 7 rows in set (0.00 sec)

DECLARE Statement Syntax


The DECLARE statement is used to specify the various items. Its allowed only inside the BEGIN.END compound statements. Declarations must follow the order like Cursor must be declare before declaring handlers and the variables and conditions must be declare before declaring either handler or cursors DECLARE Local Variable The general syntax of declaring local variable is : DECLARE var_name[,...] type [DEFAULT value] DECLARE statement is used for declaring the local variables. DEFAULT clause is used for providing a default value to the variable but if this clause is missing then the initial value is NULL. Local variable scope is limited within the BEGIN.END compound block. Variable SET Statement The general syntax of Variable SET statement is:

SET var_name = expr [, var_name = expr] ... In stored procedure SET statement is extended version of general SET statement and its implements as part of the preexisting SET Syntax. It allows an extended syntax of j=a , k=b.. where different variables types (like local variables, global variables etc) can be mixed. SELECT......INTO Statement Syntax The general syntax of SELECT....INTO Statement is: SELECT column_name1,column_name2[...] INTO var_name1,var_name2[....] table_expr This SELECT statement is used to store selected columns into variables. But by this we can retrieve only single row. The number of columns and the number of variable name must be same in this statement. In the following example we are demonstrating you the use of all above three statement. Example :
mysql> delimiter // mysql> CREATE PROCEDURE Sproced(OUT p VARCHAR(20),OUT p1 VARCHAR(20),IN p2 INT) -> BEGIN -> DECLARE a VARCHAR(20); -> DECLARE b INT; -> SET b=p2; -> SET a='Dev%'; -> SELECT * FROM Emp WHERE Designation LIKE a; -> SELECT Ename,City INTO p,p1 FROM Emp WHERE Eid=b; -> END -> // Query OK, 0 rows affected (0.07 sec) mysql> delimiter ; mysql> CALL Sproced(@Name,@City,5); +-----+-------+---------+-------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks | +-----+-------+---------+-------------+--------+-------+ | 5 | Tapan | Pune | Developer | 20600 | 1111 | | 6 | Amar | Chennai | Developer | 16000 | 1124 | +-----+-------+---------+-------------+--------+-------+ 2 rows in set (0.05 sec) Query OK, 0 rows affected (0.10 sec) mysql> SELECT @Name,@City; +-------+-------+ | @Name | @City | +-------+-------+ | Tapan | Pune | +-------+-------+ 1 row in set (0.01 sec)

Conditions and Handlers


Some conditions needs specific handling and these conditions can be related to errors or may be general flow control inside a routine. Handlers are the methods of handling conditions that need to be dealt with. Before describing conditions and handlers lets try to produce some errors. Example :

mysql> INSERT INTO Emp VALUES(1,'AAA','Delhi','Manager',20000,583); ERROR 1062 (23000): Duplicate entry '1' for key 1

In the above example MySQL produced an error, ERROR 1062. And the number between the brackets (23000) is the SQLSTATE that can be the same for a number of errors. Another example :
mysql> INSERT INTO Emp VALUES(11,NULL,'Delhi','Manager',20000,583); ERROR 1048 (23000): Column 'Ename' cannot be null

But in this example we get a different error number 1048 but the same SQLSTATE. If these errors occur in our functions and procedures then they will terminate out programs. To deal with these conditions we have to create a handler. The general syntax of Handler is as follows: DECLARE handler_type HANDLER FOR condition_value[,...] statement Firstly we have to use DECLARE for creating a handler, handler_type can be of the following like CONTINUE, EXIT or UNDO. If we are using CONTINUE the the program will carry on the process after the handler has been called. When we are using EXIT then the program will end immediately. The UNDO is used on transactional tables to rollback work carried out up to that point. HANDLER FOR tells the compiler, we are declaring a handler. Condition_value is used so that the handler fires when a define conditions met. The statement is section of code that we want to execute when the handler is fired. Now we are creating a simple procedure and in this we are trying to deal with duplicate entry. In this procedure we are not handling the error. Example :
mysql> delimiter // mysql> CREATE PROCEDURE hproc(OUT p VARCHAR(30)) -> BEGIN -> INSERT INTO Emp VALUES(1,'aaa','Delhi','Manager',20000,535); -> SET p='Can not Insert'; -> END -> // Query OK, 0 rows affected (0.19 sec) mysql> delimiter ; mysql> CALL hproc(@b); ERROR 1062 (23000): Duplicate entry '1' for key 1 mysql> SELECT @b; +------+ | @b | +------+ | | +------+ 1 row in set (0.02 sec)

In the above example we got the error message but our parameter is empty because error stopped the procedure. But if we wouldnt want that then we must use handler. In the following example lets include a handler to the procedure. Example :
mysql> mysql> -> -> -> -> -> -> delimiter // CREATE PROCEDURE hproc(OUT p VARCHAR(35)) BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @b=' With Errors'; INSERT INTO Emp VALUES(1,'AAA','Delhi','Manager',20000,698); SET p=CONCAT('Can not Insert ',@b); END //

Query OK, 0 rows affected (0.00 sec) mysql> delimiter ; mysql> CALL hproc(@c); Query OK, 0 rows affected (0.00 sec) mysql> SELECT @c; +---------------------------+ | @c | +---------------------------+ | Can not Insert With Errors| +---------------------------+ 1 row in set (0.00 sec)

Now in this example we didnt get the error message and our parameter also passed out the value because when the error occurred then handler deal with the problem and continue the procedure processing. In the above example we are using a handler to deal with SQLSTATE but the handler can deal with a set of different errors. Now in the following example we are taking the different error numbers but they had the same SQLSTATE that situation we looked at earlier. Example :
mysql> delimiter // mysql> CREATE PROCEDURE hproc(OUT p VARCHAR(35)) -> BEGIN -> DECLARE CONTINUE HANDLER FOR 1062 SET @b=' With Error 1062'; -> DECLARE CONTINUE HANDLER FOR 1048 SET @b=' With Error 1048'; -> INSERT INTO Emp VALUES(1,'AAA','Delhi','Manager',20000,698); -> SET p=CONCAT('Can not Insert',@b); -> END -> // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ; mysql> CALL hproc(@c); Query OK, 0 rows affected (0.00 sec) mysql> SELECT @c; +--------------------------------+ | @c | +--------------------------------+ | Can not Insert With Error 1062 | +--------------------------------+ 1 row in set (0.01 sec) mysql> DROP PROCEDURE hproc; Query OK, 0 rows affected (0.09 sec) mysql> mysql> -> -> -> -> -> -> -> delimiter // CREATE PROCEDURE hproc(OUT p VARCHAR(35)) BEGIN DECLARE CONTINUE HANDLER FOR 1062 SET @b=' With Error 1062'; DECLARE CONTINUE HANDLER FOR 1048 SET @b=' With Error 1048'; INSERT INTO Emp VALUES(11,NULL,'Delhi','Manager',20000,698); SET p=CONCAT('Can not Insert',@b); END //

Query OK, 0 rows affected (0.09 sec) mysql> delimiter ; mysql> CALL hproc(@c); Query OK, 0 rows affected (0.04 sec) mysql> SELECT @c; +--------------------------------+ | @c | +--------------------------------+ | Can not Insert With Error 1048 | +--------------------------------+ 1 row in set (0.03 sec)

In the above section we have seen how we can handle various conditions. Additionally MySQL allows us to define our own named conditions. But these conditions only be linked to SQLSTATE values or mysql_error_code. Syntax for creating a conditions is as follows : DECLARE condition_name CONDITION FOR condition_value condition_value can be the SQLSTATE [value] or mysql_error_code. In the following example we are describing how we can create a condition and how we can use it within a handler. Example :
mysql> delimiter // mysql> CREATE PROCEDURE condproc(OUT p VARCHAR(35)) -> BEGIN -> DECLARE duplicate CONDITION FOR SQLSTATE '23000'; -> DECLARE CONTINUE HANDLER FOR duplicate SET @b=' With Duplicate Error'; -> INSERT INTO Emp VALUES(1,'AAA','Delhi','Manager',20000,568); -> SET p=CONCAT('Can not Insert',@b); -> END -> // Query OK, 0 rows affected (0.12 sec) mysql> CALL condproc(@c); -> // Query OK, 0 rows affected (0.14 sec) mysql> delimiter ; mysql> CALL condproc(@c); Query OK, 0 rows affected (0.00 sec) mysql> SELECT @c; +-------------------------------------+ | @c | +-------------------------------------+ | Can not Insert With Duplicate Error | +-------------------------------------+ 1 row in set (0.00 sec)

In the following example we are using error code. Example :


mysql> mysql> -> -> -> -> delimiter // CREATE PROCEDURE condproc(OUT p VARCHAR(35)) BEGIN DECLARE not_null CONDITION FOR 1048; DECLARE CONTINUE HANDLER FOR not_null SET @b=' With Not Null Error'; INSERT INTO Emp VALUES(11,NULL,'Delhi','Manager',20000,698);

-> SET p=CONCAT('Can not Insert',@b); -> END -> // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ; mysql> CALL condproc(@c); Query OK, 0 rows affected (0.00 sec) mysql> SELECT @c; +------------------------------------+ | @c | +------------------------------------+ | Can not Insert With Not Null Error | +------------------------------------+ 1 row in set (0.00 sec)

TRIGGERS
A Trigger is a named database object which defines some action that the database should take when some databases related event occurs. Triggers are executed when you issues a data manipulation command like INSERT, DELETE, UPDATE on a table for which the trigger has been created. They are automatically executed and also transparent to the user. But for creating the trigger the user must have the CREATE TRIGGER privilege. In this section we will describe you about the syntax to create and drop the triggers and describe you some examples of how to use them. CREATE TRIGGER The general syntax of CREATE TRIGGER is : CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_statement

By using above statement we can create the new trigger. The trigger can associate only with the table name and that must be refer to a permanent table. Trigger_time means trigger action time. It can be BEFORE or AFTER. It is used to define that the trigger fires before or after the statement that executed it. Trigger_event specifies the statement that executes the trigger. The trigger_event can be any of the DML Statement : INSERT, UPDATE, DELETE. We can not have the two trigger for a given table, which have the same trigger action time and event. For Instance : we cannot have two BEFORE INSERT triggers for same table. But we can have a BEFORE INSERT and BEFORE UPDATE trigger for a same table. Trigger_statement have the statement that executes when the trigger fires but if you want to execute multiple statement the you have to use the BEGINEND compound statement. We can refer the columns of the table that associated with trigger by using the OLD and NEW keyword. OLD.column_name is used to refer the column of an existing row before it is deleted or updated and NEW.column_name is used to refer the column of a new row that is inserted or after updated existing row. In INSERT trigger we can use only NEW.column_name because there is no old row and in a DELETE trigger we can use only OLD.column_name because there is no new row. But in UPDATE trigger we can use both, OLD.column_name is used to refer the columns of a row before it is updated and NEW.Column_name is used to refer the column of the row after it is updated. In the following example we are updating the Salary column of Employee table before inserting any record in Emp table. Example :
mysql> SELECT * FROM Employee; +-----+---------+----------+-------------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks | +-----+---------+----------+-------------------+--------+-------+ | 1 | Rahul | Delhi | Manager | 10300 | 853 | | 2 | Gaurav | Mumbai | Assistant Manager | 10300 | 853 | | 3 | Chandan | Banglore | Team Leader | 15450 | 999 | | 5 | Tapan | Pune | Developer | 20600 | 1111 | | 6 | Amar | Chennai | Developer | 16000 | 1124 | | 7 | Santosh | Delhi | Designer | 10000 | 865 | | 8 | Suman | Pune | Web Designer | 20000 | 658 | +-----+---------+----------+-------------------+--------+-------+ 7 rows in set (0.00 sec) mysql> delimiter // mysql> CREATE TRIGGER ins_trig BEFORE INSERT ON Emp -> FOR EACH ROW -> BEGIN -> UPDATE Employee SET Salary=Salary-300 WHERE Perks>500; -> END; -> // Query OK, 0 rows affected (0.01 sec) mysql> delimiter ; mysql> INSERT INTO Emp VALUES(9,'Rajesh','Delhi','Developer',15000,658); Query OK, 1 row affected (0.05 sec) mysql> SELECT * FROM Employee; +-----+---------+----------+-------------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks |

+-----+---------+----------+-------------------+--------+-------+ | 1 | Rahul | Delhi | Manager | 10000 | 853 | | 2 | Gaurav | Mumbai | Assistant Manager | 10000 | 853 | | 3 | Chandan | Banglore | Team Leader | 15150 | 999 | | 5 | Tapan | Pune | Developer | 20300 | 1111 | | 6 | Amar | Chennai | Developer | 15700 | 1124 | | 7 | Santosh | Delhi | Designer | 9700 | 865 | | 8 | Suman | Pune | Web Designer | 19700 | 658 | +-----+---------+----------+-------------------+--------+-------+ 7 rows in set (0.00 sec)

In the following example we are modifying the salary of Employee table before updating the record of the same table. Example :
mysql> delimiter // mysql> CREATE TRIGGER updtrigger BEFORE UPDATE ON Employee -> FOR EACH ROW -> BEGIN -> IF NEW.Salary<=500 THEN -> SET NEW.Salary=10000; -> ELSEIF NEW.Salary>500 THEN -> SET NEW.Salary=15000; -> END IF; -> END -> // Query OK, 0 rows affected (0.01 sec) mysql> delimiter ; mysql> UPDATE Employee -> SET Salary=500; Query OK, 5 rows affected (0.04 sec) Rows matched: 7 Changed: 5 Warnings: 0 mysql> SELECT * FROM Employee; +-----+---------+----------+-------------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks | +-----+---------+----------+-------------------+--------+-------+ | 1 | Rahul | Delhi | Manager | 10000 | 853 | | 2 | Gaurav | Mumbai | Assistant Manager | 10000 | 853 | | 3 | Chandan | Banglore | Team Leader | 10000 | 999 | | 5 | Tapan | Pune | Developer | 10000 | 1111 | | 6 | Amar | Chennai | Developer | 10000 | 1124 | | 7 | Santosh | Delhi | Designer | 10000 | 865 | | 8 | Suman | Pune | Web Designer | 10000 | 658 | +-----+---------+----------+-------------------+--------+-------+ 7 rows in set (0.00 sec) mysql> UPDATE Employee -> SET Salary=1500; Query OK, 7 rows affected (0.03 sec) Rows matched: 7 Changed: 7 Warnings: 0 mysql> SELECT * FROM Employee; +-----+---------+----------+-------------------+--------+-------+ | Eid | Ename | City | Designation | Salary | Perks | +-----+---------+----------+-------------------+--------+-------+ | 1 | Rahul | Delhi | Manager | 15000 | 853 | | 2 | Gaurav | Mumbai | Assistant Manager | 15000 | 853 |

| 3 | Chandan | Banglore | Team Leader | 15000 | 999 | | 5 | Tapan | Pune | Developer | 15000 | 1111 | | 6 | Amar | Chennai | Developer | 15000 | 1124 | | 7 | Santosh | Delhi | Designer | 15000 | 865 | | 8 | Suman | Pune | Web Designer | 15000 | 658 | +-----+---------+----------+-------------------+--------+-------+ 7 rows in set (0.01 sec)

DROP TRIGGER The general syntax of DROP TRIGGER is : DROP TRIGGER trigger_name This statement is used to drop a trigger. Example of Dropping the Trigger :
mysql> DROP TRIGGER updtrigger; Query OK, 0 rows affected (0.02 sec)

Views
VIEW is a virtual table, which acts like a table but actually it contains no data. That is based on the result set of a SELECT statement. A VIEW consists rows and columns from one or more than one tables. A VIEW is a query thats stored as an object. A VIEW is nothing more than a way to select a subset of tables columns. When you defined a view then you can reference it like any other table in a database. A VIEW provides as a security mechanism also. VIEWS ensures that users are able to modify and retrieve only that data which seen by them. By using Views you can ensure about the security of data by restricting access to the following data: Specific columns of the tables. Specific rows of the tables. Specific rows and columns of the tables. Subsets of another view or a subset of views and tables Rows fetched by using joins. Statistical summary of data in a given tables.

CREATE VIEW Statement CREATE VIEW Statement is used to create a new database view. The general syntax of CREATE VIEW Statement is: CREATE VIEW view_name [(column_list)] [WITH ENCRYPTION] AS select_statement [WITH CHECK OPTION] View_name specifies the name for the new view. column_list specifies the name of the columns to be used in view. column_list must have the same number of columns that specified in select_statement. If column_list option is not available then view is created with the same columns that specified in select_statement.

WITH ENCRYPTION option encrypts the text to the view in the syscomments table. AS option specifies the action that is performed by the view. select_statement is used to specify the SELECT statement that defines a view. The optional WITH CHECK OPTION clause applies to the data modification statement like INSERT and UPDATE statements to fulfill the criteria given in the select_statement defining the view. This option also ensures that the data can visible after the modifications are made permanent. Some restrictions imposed on views are given below : A view can be created only in the current database. The view name must follow the rules for identifiers and The view name must not be the same as that of the base table A view can be created only that time if there is a SELECT permission on its base table. A SELECT INTO statement cannot be used in view declaration statement. A trigger or an index cannot be defined on a view. The CREATE VIEW statement cannot be combined with other SQL statements in a single batch.

Example : In the following example we have two table Client and Products. And if you want to see only those client records that are active in Products table also means right now they are supplying us the products. For this we are creating the view by the name of Supp_Client.
mysql> SELECT * FROM Client; +------+---------------+----------+ | C_ID | Name | City | +------+---------------+----------+ | 1 | A K Ltd | Delhi | | 2 | V K Associate | Mumbai | | 3 | R K India | Banglore | | 4 | R S P Ltd | Kolkata | | 5 | A T Ltd | Delhi | | 6 | D T Info | Delhi | +------+---------------+----------+ 6 rows in set (0.00 sec) mysql> SELECT * FROM Products; +---------+-------------+------+ | Prod_ID | Prod_Detail | C_ID | +---------+-------------+------+ | 111 | Monitor | 1 | | 112 | Processor | 2 | | 113 | Keyboard | 2 | | 114 | Mouse | 3 | | 115 | CPU | 5 | +---------+-------------+------+ 5 rows in set (0.00 sec)

Example : Create View Statement


mysql> -> -> -> -> CREATE VIEW Supp_Client AS SELECT * FROM Client WHERE C_ID IN ( SELECT C_ID FROM Products) WITH CHECK OPTION;

Query OK, 0 rows affected (0.05 sec) mysql> SELECT * FROM Supp_Client; +------+---------------+----------+ | C_ID | Name | City | +------+---------------+----------+ | 1 | A K Ltd | Delhi | | 2 | V K Associate | Mumbai | | 3 | R K India | Banglore | | 5 | A T Ltd | Delhi | +------+---------------+----------+ 4 rows in set (0.03 sec)

In the following example we include the WHERE clause with the select statement of view. Then MySQL adds this condition to the VIEW definition when executing the statement for further restricting the result. Example :
mysql> SELECT * FROM Supp_Client WHERE City='Delhi'; +------+---------+-------+ | C_ID | Name | City | +------+---------+-------+ | 1 | A K Ltd | Delhi | | 5 | A T Ltd | Delhi | +------+---------+-------+ 2 rows in set (0.04 sec)

ALTER VIEW Statement By the ALTER VIEW Statement we can change the definition of a view. This statement is useful to modify a view without dropping it. ALTER VIEW statement syntax is similar to CREATE VIEW Statement and effect is same as the CREATE OR REPLACE VIEW. The general syntax of ALTER VIEW Statement is : ALTER VIEW view_name [(column_list)] [WITH ENCRYPTION] AS select_statement [WITH CHECK OPTION] In the following example we are altering the view definition that we have created above. In this we add one more column by the name of Prod_Detail of Products table. Example of Altering the View Statement :
mysql> ALTER VIEW Supp_Client AS -> SELECT Client.C_ID, Client.Name, Client.City, -> Products.Prod_Detail from Client, Products -> WHERE Client.C_ID=Products.C_ID; Query OK, 0 rows affected (0.01 sec) mysql> SELECT * FROM Supp_Client; +------+---------------+----------+-------------+ | C_ID | Name | City | Prod_Detail | +------+---------------+----------+-------------+ | 1 | A K Ltd | Delhi | Monitor | | 2 | V K Associate | Mumbai | Processor | | 2 | V K Associate | Mumbai | Keyboard | | 3 | R K India | Banglore | Mouse | | 5 | A T Ltd | Delhi | CPU | +------+---------------+----------+-------------+ 5 rows in set (0.02 sec)

DROP VIEW Statement For dropping a view you can use the DROP VIEW Statement. When view is dropped but it has no

effect on the underlying tables. After dropping a view if you issue any query that reference a dropped view then you get an error message. But dropping a table that reference any view does not drop the view automatically you have to dropt the view explicitly. The general syntax of DROP VIEW Statement is : DROP VIEW view_name; In the following example we are dropping the view that we have created above. Example of Dropping the View Statement :
mysql> DROP VIEW Supp_Client; Query OK, 0 rows affected (0.00 sec) mysql> SELECT * FROM Supp_Client; ERROR 1146 (42S02): Table 'employee.supp_client' doesn't exist

Você também pode gostar