Create a stored procedure for MySQL

Source: Internet
Author: User
Tags case statement decimal to binary

Create a stored procedure for MySQL

Mysql stored procedure details

1. Introduction to stored procedures

The commonly used operating database language SQL statements must be compiled and then executed before execution. The Stored Procedure (StoredProcedure) is a set of SQL statements for specific functions, after compilation, the stored procedure is stored in the database. You can call and execute the stored procedure by specifying the name of the stored procedure and specifying parameters (if the stored procedure has parameters.

A stored procedure is a Programmable function that is created and saved in a database. It can contain SQL statements and some special control structures. Stored procedures are useful when you want to execute the same functions on different applications or platforms or encapsulate specific functions. Stored Procedures in databases can be seen as simulation of object-oriented methods in programming. It allows you to control how data is accessed.

Stored procedures generally have the following advantages:

(1) stored procedures enhance the functionality and flexibility of the SQL language. Stored procedures can be written using flow control statements. With great flexibility, they can complete complicated judgment and computation.

(2) stored procedures allow standard components to be programmed. After a stored procedure is created, it can be called multiple times in the program without having to rewrite the SQL statement of the stored procedure. Database professionals can modify the stored procedure at any time without affecting the application source code.

(3). the stored procedure can achieve fast execution speed. If an operation contains a large number of Transaction-SQL code or is executed multiple times, the stored procedure is much faster than the batch processing. Because the stored procedure is pre-compiled. When a stored procedure is run for the first time, the optimizer analyzes and optimizes it and provides an execution plan that is finally stored in the system table. The Transaction-SQL statement of batch processing needs to be compiled and optimized each time it is run, which is relatively slow.

(4). stored procedures can reduce network traffic. For operations (such as queries and modifications) on the same database object, if the Transaction-SQL statement involved in this operation is organized by the stored procedure, when the stored procedure is called on the client's computer, the call statement is transmitted on the network, which greatly increases network traffic and reduces network load.

(5) stored procedures can be fully utilized as a security mechanism. By limiting the permissions of a stored procedure, the system administrator can restrict the data access permissions to avoid unauthorized users accessing data, this ensures data security.

2. MySQL stored procedures

Stored procedures are an important function of database storage. However, MySQL did not support stored procedures before MySQL 5.0, which greatly compromises the application of MySQL. Fortunately, MySQL 5.0 has finally started to support stored procedures, which can greatly improve the processing speed of the database and the flexibility of database programming.

3. MySQLCreate a stored procedure

(1). Format

Format of MySQL stored PROCEDURE creation: create procedure process name ([process parameter [,...])
[Features...] process body

Here is an example:

Mysql> DELIMITER // mysql> create procedure proc1 (OUT s int)-> BEGIN-> select count (*) INTO s FROM user; -> END-> // mysql> DELIMITER;

(1) Here we need to note that DELIMITER // and DELIMITER; the DELIMITER means DELIMITER, because MySQL uses ";" as the Separator by default, if we do not declare a DELIMITER, the compiler treats the stored procedure as an SQL statement, and the compilation process of the stored procedure reports an error. Therefore, we must first use the DELIMITER keyword to declare the DELIMITER of the current segment, in this way, MySQL regards ";" as the code in the stored procedure and does not execute the code. After the code is used up, the separator should be restored.

(2) The stored procedure may have input, output, and input and output parameters as needed. Here there is an output parameter s in the type of int. If there are multiple parameters, use ", "Split.

(3) start and END of the Process body are identified by BEGIN and END.

In this way, a MySQL stored procedure is completed, isn't it easy? It doesn't matter if you don't understand it. Next, Let's explain it in detail.

(2). Declare the delimiter

As a matter of fact, the above annotations have been clearly written about the Declaration delimiter. You don't need to say much, but note that if you use the MySQL Administrator management tool, it can be created directly without declaration.

(3). Parameters

MySQL stored procedure parameters are used IN the definition of stored procedures. There are three parameter types: IN, OUT, And INOUT. The format is as follows:

CREATEPROCEDURE ([[IN | OUT | INOUT] Parameter Name Data class...])

IN input parameters:Indicates that the value of this parameter must be specified when the stored procedure is called. Modifying the value of this parameter in the stored procedure cannot be returned, which is the default value.

OUT output parameters:This value can be changed within the stored procedure and can be returned

INOUT input and output parameters:Can be changed and returned.

I. IN parameter example


Mysql> DELIMITER // mysql> create procedure demo_in_parameter (IN p_in int)-> BEGIN-> SELECT p_in;-> SET p_in = 2;-> SELECT p_in;-> END; -> // mysql> DELIMITER;

Execution result:

Mysql> SET @ p_in = 1; mysql> CALL demo_in_parameter (@ p_in ); + ------ + | p_in | + ------ + | 1 | + ------ ++ ------ + | p_in | + ------ + | 2 | + ------ + mysql> SELECT @ p_in; + ------- + | @ p_in | + ------- + | 1 | + ------- +

As shown above, although p_in is modified in the stored procedure, it does not affect the value of @ p_id.

Example of the II. OUT Parameter


Mysql> DELIMITER // mysql> create procedure demo_out_parameter (OUT p_out int)-> BEGIN-> SELECT p_out;-> SET p_out = 2;-> SELECT p_out;-> END; -> // mysql> DELIMITER;

Execution result:

Mysql> SET @ p_out = 1; mysql> CALL sp_demo_out_parameter (@ p_out ); + ------- + | p_out | + ------- + | NULL | + ------- ++ ------- + | p_out | + ------- + | 2 | + ------- + mysql> SELECT @ p_out; + ------- + | p_out | + ------- + | 2 | + ------- +

Iii. Example of INOUT Parameters


Mysql> DELIMITER // mysql> create procedure demo_inout_parameter (INOUT p_inout int)-> BEGIN-> SELECT p_inout;-> SET p_inout = 2;-> SELECT p_inout;-> END; -> // mysql> DELIMITER;



Execution result:
Mysql> SET @ p_inout = 1; mysql> CALL demo_inout_parameter (@ p_inout ); + --------- + | p_inout | + --------- + | 1 | + --------- ++ --------- + | p_inout | + --------- + | 2 | + --------- + mysql> SELECT @ p_inout; + ---------- + | @ p_inout | + ---------- + | 2 | + ---------- +

(4). Variables

I. variable definition

DECLARE variable_name [, variable_name...] datatype [DEFAULT value];

Datatype is the data type of MySQL, such as int, float, date, varchar (length)

For example:

DECLARE l_int int unsigned default 4000000; DECLARE l_numeric number (9.95) DEFAULT 1999; DECLARE l_date DEFAULT '2017-12-31 '; DECLARE l_datetime DEFAULT '2017-12-31 23:59:59 '; DECLARE l_varchar varchar (255) DEFAULT 'this will not be padded ';
Ii. Variable assignment

SET variable name = expression value [, variable_name = expression...]

Iii. User Variables

I. Use user variables on the MySQL client

Mysql> SELECT 'Hello world' into @ x; mysql> SELECT @ x; + ------------- + | @ x | + ------------- + | Hello World | + ------------- + mysql> SET @ y = 'Goodbye Cruel world'; mysql> SELECT @ y; + --------------------- + | @ y | + --------------------- + | Goodbye Cruel World | + --------------------- + mysql> SET @ z = 1 + 2 + 3; mysql> SELECT @ z; + ------ + | @ z | + ------ + | 6 | + ------ +

Ii. Use user variables in Stored Procedures

Mysql> create procedure GreetWorld () select concat (@ greeting, 'World'); mysql> SET @ greeting = 'hello'; mysql> CALL GreetWorld (); + -------------------------- + | CONCAT (@ greeting, 'World') | + ------------------------------ + | Hello World | + ------------------------------ +
Iii. Pass global user variables between stored procedures
Mysql> create procedure p1 () SET @ last_procedure = 'p1'; mysql> create procedure p2 () select concat ('Last procedure was', @ last_proc ); mysql> CALL p1 (); mysql> CALL p2 (); + ----------------------------------------------- + | CONCAT ('Last procedure was ', @ last_proc | + --------------------------------------------- + | Last procedure was p1 | + --------------------------------------------- +

① User variable names generally start @

② Misuse of user variables will make the program hard to understand and manage

(5). Comment

MySQL stored procedures can be annotated using two styles

Dual-mode bar :--

This style is generally used for single-line comments.

C style: generally used for multi-line comments

For example:

Mysql> DELIMITER // mysql> create procedure proc1 -- name stored PROCEDURE name-> (IN parameter1 INTEGER)-> BEGIN-> DECLARE variable1 CHAR (10 ); -> IF parameter1 = 17 THEN-> SET variable1 = 'birds ';-> ELSE-> SET variable1 = 'beasts';-> end if; -> insert into table1 VALUES (variable1);-> END-> // mysql> DELIMITER;

4. MySQLStored Procedure Call

Use the call and your process name and a bracket. Add parameters in the brackets as needed, including input parameters, output parameters, and input and output parameters. For details about the call method, refer to the example above.

5. MySQLQuery stored procedures

As we know the tables under a database, we generally use showtables; for viewing. So can we check whether the stored procedures under a database can be used as well? The answer is: we can view the stored procedures under a database, but it takes only one minute.

We can use

Select namefrom mysql. proc where db = 'database name ';


Selectroutine_name from information_schema.routines whereroutine_schema = 'database name ';


Show procedurestatus where db = 'database name ';


If we want to know the details of a stored procedure, what should we do? Can I use the describe table name for viewing like an operation table?

The answer is: we can view the details of the stored procedure, but we need to use another method:

Show createprocedure database. Name of the stored procedure;

You can view the details of the current stored procedure.

6. MySQLStored Procedure Modification


Change the pre-specified stored PROCEDURE created with create procedure without affecting the stored PROCEDURE or function.

7. MySQLDelete stored procedure

Deleting a stored procedure is simple, just like deleting a table:


Delete one or more stored procedures from a MySQL table.

8. MySQLStored Procedure control statements

(1). variable scope

Internal variables have a higher priority within the scope of their scope, when executed to the end. The internal variable disappears and is out of its scope, and the variable is no longer visible.
The declarative variable can no longer be found outside the process, but you can use the out parameter or assign its value
Session variables to save their values.

Mysql> DELIMITER // mysql> create procedure proc3 ()-> begin-> declare x1 varchar (5) default 'outer';-> begin-> declare x1 varchar (5) default 'inner ';-> select x1;-> end;-> select x1;-> end;-> // mysql> DELIMITER;

(2). Condition Statement

I. if-then-else statement

Mysql> DELIMITER // mysql> create procedure proc2 (IN parameter int)-> begin-> declare var int;-> set var = parameter + 1; -> if var = 0 then-> insert into t values (17);-> end if;-> if parameter = 0 then-> update t set s1 = s1 + 1; -> else-> update t set s1 = s1 + 2;-> end if;-> end;-> // mysql> DELIMITER;

Ii. case statement:

Mysql> DELIMITER // mysql> create procedure proc3 (in parameter int)-> begin-> declare var int;-> set var = parameter + 1; -> case var-> when 0 then-> insert into t values (17);-> when 1 then-> insert into t values (18 ); -> else-> insert into t values (19);-> end case;-> end;-> // mysql> DELIMITER;

(3). Loop statement

I. while... endwhile:

Mysql> DELIMITER // mysql> create procedure proc4 ()-> begin-> declare var int;-> set var = 0; -> while var <6 do-> insert into t values (var);-> set var = var + 1;-> end while;-> end; -> // mysql> DELIMITER;

Ii. repeat · endrepeat:

It checks the result after the operation is executed, while it checks before the execution.

Mysql> DELIMITER // mysql> create procedure proc5 ()-> begin-> declare v int;-> set v = 0; -> repeat-> insert into t values (v);-> set v = v + 1;-> until v> = 5-> end repeat;-> end; -> // mysql> DELIMITER;

Iii. loop · endloop:

The loop does not require the initial conditions. This is similar to the while loop, and does not require the end condition like the repeat loop. The leave statement is used to exit the loop.

Mysql> DELIMITER // mysql> create procedure proc6 ()-> begin-> declare v int;-> set v = 0;-> LOOP_LABLE: loop-> insert into t values (v);-> set v = v + 1;-> if v> = 5 then-> leave LOOP_LABLE;-> end if; -> end loop;-> end;-> // mysql> DELIMITER;

Iv. LABLES labels:

The label can be used before the begin repeat while or loop statement. The statement label can only be used before a valid statement. You can jump out of the loop to make the running command the last step of the compound statement.

(4). ITERATE Iteration


Reference the compound statement label to start a compound statement.

Mysql> DELIMITER // mysql> create procedure proc10 ()-> begin-> declare v int;-> set v = 0;-> LOOP_LABLE: loop-> if v = 3 then-> set v = v + 1;-> ITERATE LOOP_LABLE;-> end if;-> insert into t values (v ); -> set v = v + 1;-> if v> = 5 then-> leave LOOP_LABLE;-> end if;-> end loop;-> end; -> // mysql> DELIMITER;

9. MySQLBasic functions of Stored Procedures

(1). string type

CHARSET (str) // returns the string Character Set
CONCAT (string2 [,...]) // connection string
INSTR (string, substring) // returns the position of the first occurrence of the substring in the string. If no position exists, 0 is returned.
LCASE (string2) // converts it to lowercase
LEFT (string2, length) // take the length from the LEFT of string2
LENGTH (string) // string LENGTH
LOAD_FILE (file_name) // read content from the file
LOCATE (substring, string [, start_position]) is the same as INSTR, but the start position can be specified.
LPAD (string2, length, pad) // repeat pad to start with string until the string length is length
LTRIM (string2) // remove leading Spaces
REPEAT (string2, count) // REPEAT count times
REPLACE (str, search_str, replace_str) // REPLACE search_str with replace_str in str
RPAD (string2, length, pad) // use pad after str until the length is length.
RTRIM (string2) // remove backend Spaces
STRCMP (string1, string2) // compare the size of two strings by character,
SUBSTRING (str, position [, length]) // starts from the position of str and takes length characters,
Note: When processing strings in mysql, the default subscript of the first character is 1, that is, the parameter position must be greater than or equal to 1.

Mysql> select substring ('abcd',); + ----------------------- + | substring ('abcd) | + ----------------------- + | + --------------------- + 1 row in set (0.00 sec) mysql> select substring ('abcd',); + --------------------- + | substring ('abcd ', 1, 2) | + --------------------- + | AB | + ----------------------- + 1 row in set (0.02 sec)

TRIM ([[BOTH | LEADING | TRAILING] [padding] FROM] string2) // remove the specified character FROM the specified position
UCASE (string2) // converts to uppercase
RIGHT (string2, length) // gets the last length character of string2
SPACE (count) // generate count Spaces

(2). Mathematics

ABS (number2) // absolute value
BIN (decimal_number) // convert decimal to binary
CEILING (number2) // rounded up
CONV (number2, from_base, to_base) // hexadecimal conversion
FLOOR (number2) // round down
FORMAT (number, decimal_places) // number of reserved decimal places
HEX (DecimalNumber) // convert to hexadecimal
Note: HEX () can input a string, returns its ASC-11 code, such as HEX ('def ') returns 4142143
You can also input a decimal integer to return its hexadecimal encoding. For example, HEX (25) returns 19.
LEAST (number, number2 [,...]) // calculates the minimum value.
MOD (numerator, denominator) // evaluate the remainder
POWER (number, power) // Exponent
RAND ([seed]) // Random Number
ROUND (number [, decimals]) // rounding, decimals is the number of decimal places]

Note: The return type is not an integer, for example:
(1) The default value is integer.

Mysql> select round (1.23); + ------------- + | round (1.23) | + ------------- + | 1 | + ------------- + 1 row in set (0.00 sec) mysql> select round (1.56); + ------------- + | round (1.56) | + ------------- + | 2 | + ------------- + 1 row in set (0.00 sec)

(2) the number of decimal places can be set to return floating point data.

Mysql> select round (1.567, 2); + ---------------- + | round (1.567, 2) | + ---------------- + | 1.57 | + ---------------- + 1 row in set (0.00 sec)

SIGN (number2 )//

(3). Date and Time

ADDTIME (date2, time_interval) // Add time_interval to date2
CONVERT_TZ (datetime2, fromTZ, toTZ) // convert the time zone
CURRENT_DATE () // current date
CURRENT_TIME () // current time
CURRENT_TIMESTAMP () // current Timestamp
DATE (datetime) // return the DATE part of datetime
DATE_ADD (date2, INTERVAL d_value d_type) // Add a date or time in date2
DATE_FORMAT (datetime, FormatCodes) // display datetime in formatcodes format
DATE_SUB (date2, INTERVAL d_value d_type) // subtract a time from date2
DATEDIFF (date1, date2) // two date differences
DAY (date) // returns the DAY of the date
DAYNAME (date) // english week
DAYOFWEEK (date) // Week (1-7), 1 is Sunday
DAYOFYEAR (date) // The day of the year
EXTRACT (interval_name FROM date) // EXTRACT the specified part of the date FROM date
MAKEDATE (year, day) // specifies the day of the year and year to generate a date string.
MAKETIME (hour, minute, second) // generate a time string
MONTHNAME (date) // name of the English month
NOW () // current time
SEC_TO_TIME (seconds) // converts seconds to time
STR_TO_DATE (string, format) // convert string to time, which is displayed in format
TIMEDIFF (datetime1, datetime2) // two time difference
TIME_TO_SEC (time) // time to seconds]
WEEK (date_time [, start_of_week]) // WEEK
YEAR (datetime) // YEAR
DAYOFMONTH (datetime) // The day of the month
HOUR (datetime) // HOUR
LAST_DAY (date) // the last date of the Month of date
MONTH (datetime) // MONTH
MINUTE (datetime) // return the MINUTE sign, positive or negative or 0
SQRT (number2) // Square

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.