Kshitij’s Blog .NET/ CSLA.NET / ASP.NET / VB.NET / C# / SQL Server / MySql ..
  • Jun
    9

    Stored Procedures in MySQL

    Filed under: MySQL; Tagged as: ,


    So what exactly Stored Procedures are :

    • Basically in a database management system (DBMS), a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that’s stored in the database in compiled form so that it can be shared by a number of programs. The use of stored procedures can be helpful in controlling access to data (end-users may enter or change data but do not write procedures), preserving data integrity (information is entered in a consistent manner), and improving productivity (statements in a stored procedure only need to be written one time). Stored procedures have been part of Oracle, MS SQL Server, DB-2, postgreSQL and others for years but MySQL introduce Store procedures recently in version 5.xxx. MySQL stored procedures are very similar to the DB2 implementation, as both are based on the SQL:2003 standard.

    Why i need store procedure when i can write Queries on page/forms  :

    • Consider a scenario in which you have a client/server application with centrally located database server and your application has a provision to create a voucher and you calculate tax on the amount of the voucher. What if you need to change tax rate. Either you have to change code in your form to recalculate the tax and then you need to reinstall your forms on each of the client machine or you have an option to create a procedure that calculate tax and call that procedure from your client application and that’s it. Because your application call the procedure to calculate tax you don’t need to reinstall your BO (Business Objects) or client application to each of client machine. All you need to do is to change code in your procedure that calculate Tax.
    • They can reduce network traffic. Complex, repetitive tasks may require getting results, applying some logic to them, and using this to get more results. If this only has to be done on the database server, there is no need to send result sets and new queries back and forth from application server to database server. Network traffic is a common bottleneck causing performance issues, and stored procedures can help reduce this. More often though, it is the database server itself that is the bottleneck, so this may not be much of an advantage.

    Let’s Start with a simple Example:

    As i described earlier a store procedure is a set of SQL Statement. Almost any valid SQL Statement can go inside a store procedure, with a few exceptions, which we will look later. I am using MySQL command line utility to write and execute procedures. You can also use MySQL Query Browser to create/modify/delete procedures. It comes with MySQL GUI Tools which are freely available on MySQL Site.

    use test; #Select Database
    CREATE PROCEDURE usp_test() SELECT ‘SP Test ‘ as Title;
    This line will add a procedure called “usp_test” in your selected database which in this case is Test. Note i use ‘usp’  (User store procedure) as a prefix to procedure just to distinct it with system procedures.
    Now let’s call our newly created store procedure by using call keyword.
    Call usp_test();
    if you run this from MySQL command line utility you will get something like :

    ScreenHunter_01 Jun. 08 14.34

    The procedure we just create is hardly useful, but the basics are there. CREATE PROCEDURE sp_name() will define the procedure, and CALL sp_name() will call the procedure.

    Let’s move ahead : Parameters

    The real benefit of a stored procedure is when you can pass values to it, as well as retrieve information back. The concept of parameters should be familiar to anyone who has had experience with any procedural programming experience.

    There are three types of parameter:

    • IN: The default. This parameter is passed to the procedure, and can change inside the procedure, but remains unchanged outside.
    • OUT: No value is supplied to the procedure (it is assumed to be NULL), but it can be modified inside the procedure, and is available outside the procedure.
    • INOUT: The characteristics of both IN and OUT parameters. A value can be passed to the procedure, modified there as well as passed back again.ScreenHunter_02 Jun. 08 17.30


    An IN Example:

    Here is an example of a stored procedure demonstrating the use of an IN parameter. Since IN is the default, there is no need to specify the parameter as such.

    mysql> CREATE PROCEDURE USP_IN(p VARCHAR(10)) SET @Name = P;
    mysql> CALL USP_IN(‘KSHITIJ SHARMA’);
    mysql> SELECT @Name;
    

    And you should get something like

    ScreenHunter_01 Jun. 09 08.23


    The session variable @Name is set inside of the procedure, based upon the parameter P, which is passed to the procedure, and remains unchanged.

    An Out Example:

    ScreenHunter_02 Jun. 09 09.46

    Here I reset @Name just to make sure the final result is not a legacy of the previous procedure. This time, the parameter P is changed inside of the procedure, while the session variable is passed to the procedure, ready to receive the result.

    An In-Out Example:

    ScreenHunter_03 Jun. 09 11.10

    Here, a parameter is passed to the procedure, used in the calculation, and the results are made available to the session variable @Y.

    Getting Information from Database :

    mysql> SHOW PROCEDURE STATUS;mysql> SELECT * FROM INFORMATION_SCHEMA.ROUTINES;

    Let’s do a bit more complex example :

    First, we will create a sample table.

    mysql> CREATE table tmptest(id INT, txt VARCHAR(10), PRIMARY KEY(id));
    Query OK, 0 rows affected (0.11 sec)

    Delimiters, and multi-statement procedures

    Stored procedures of course are not that useful if they are just one statement. The effects of all the procedures we have looked at so far could have had been duplicated much more easily with a single SQL statement. Useful procedures are much longer than that. Those of you who are on the ball may be thinking of a complication. How can we differentiate between multiple statements inside the procedure, and the end of the procedure? We have to create a different delimiter to end the CREATE PROCEDURE statement. Here is how:

    mysql> DELIMITER $$

    Note that there is no semicolon after the ‘$$’ symbol, which we will use as the delimiter for our purposes. You have to choose a delimiter that does not appear in your procedure, and it can be more than one character.

    mysql> CREATE PROCEDURE usp_ins (P VARCHAR(10))
        -> BEGIN
        ->  SET @x=CHAR_LENGTH(P);
        ->  SET @y = HEX(P);
        ->  INSERT INTO tmptest(id,txt) VALUES(@x,@y);
        -> END$$
    Query OK, 0 rows affected (0.05 sec)
    
    mysql> CALL usp_ins('ABC');
        -> $$
    Query OK, 1 row affected (0.00 sec)
    mysql> DELIMITER ;
    mysql> SELECT * FROM tmptest;
    *************************** 1. row ***************************
     id: 3
    txt: 414243
    1 row in set (0.00 sec)


    Note what happened when we tried to call the procedure. Because MySQL was still using the $$ symbol as a delimiter, and not the semicolon, the statement did not run after the semicolon. We first needed to close it with the piping symbol. Afterwards, we reset the delimiter back to normal, and test that the records were correctly added to the tmptest table.

    Procedure Variables:

    You can DECLARE variables that exist only inside the procedure, as well as assign values to them with the SET statement without using the ‘@’ symbol, required for session variables. Here is how:

    mysql> DELIMITER $$
    
    mysql> CREATE PROCEDURE usp_variables (P INT)
    
    -> BEGIN->  DECLARE a INT;
    ->  DECLARE b INT DEFAULT 10;
    ->  SET a = P*b;->  INSERT INTO tmptest(id,txt) VALUES(a,HEX('DEF'));
    -> END$$ 
    
    Query OK, 0 rows affected (0.00 sec) 
    
    mysql> DELIMITER ;
    mysql> CALL usp_variables(4);
    Query OK, 1 row affected (0.00 sec) 
    mysql> SELECT * FROM tmptest;
    *************************** 1. row ***************************
     id: 3
    txt: 414243
    *************************** 2. row ***************************
     id: 40
    txt: 444546
    2 rows in set (0.00 sec)

    if you declare a variable without default (such as a ) it will be set to NULL.

    Populating Variables from table.

    mysql> DELIMITER $$
    mysql> CREATE PROCEDURE usp_selectINvariable ()
        -> BEGIN
        ->  DECLARE a INT;
        ->  DECLARE b VARCHAR(10);
        ->  SELECT id,txt INTO a,b FROM tmptest LIMIT 1;
        ->  SELECT a,b;
        -> END|
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> DELIMITER ;
    mysql> CALL usp_selectINvariable();
    *************************** 1. row ***************************
    a: 3
    b: 414243
    1 row in set (0.00 sec)
    
    Query OK, 0 rows affected (0.00 sec)

    see how i limit the result to single  (LIMIT 1)  record. In next post i will show you how to iterate multiple records.

    I hope you can now write your own store procedure in MySQL.  In next post of this series i will show you more complex topics, to show some of the real power of store procedures.

    Kshitij


    1 person likes this post.
    9 Comments

9 Responses to “Stored Procedures in MySQL”

  1. Nice post, thanks.

  2. Thanks for posting, I’ll definitely be subscribing to your blog.

  3. Hey, nice post, really well written. You should write more about this. I’ll certainly be subscribing.

  4. Hi Mke,
    I will be adding more MySQL article very soon. Thanks for appreciation.

  5. Thanks.

  6. Nice Article. Please Post More on this topic.

  7. You explain it with ease.
    Thanks

  8. Thank you very much. Your tutorial is very good.

  9. excellent illustration!
    not even a donkey dare say ‘I didn’t understand’!
    thanks

Leave a Reply