I. Stored Procedures
1.1. Basic Grammar
- CREATE PROCEDURE sp_name ([proc_parameter[,...]])
- [characteristic ...] routine_body
Where programmers share thinking
Posted by stephanie on Thu, 11 Jul 2019 01:28:00 +0200
- CREATE PROCEDURE sp_name ([proc_parameter[,...]])
- [characteristic ...] routine_body
Sp_name: The name of the stored procedure, which is created in the current database by default. This name should try to avoid the same name as MySQL's built-in functions
Proc_parameter: A list of stored procedure parameters
Format [IN|OUT|INOUT]param_name type
Param_name is the parameter name and type is the data type of the parameter. Multiple parameters are separated by commas. Input parameters, output parameters and input/output parameters are identified by in/out/inout, respectively. The name of the parameter should not be the same as the column name of the table.
Characteristic: Some feature settings for stored procedures are introduced separately
COMMENT'string': Used to describe stored procedures, where string is the description content and comment is the keyword.
2 LANGUAGE SQL: specifies that the language in which the stored procedure is written is the SQL language. This option may not be specified.
DETERMINISTIC: Represents that stored procedures produce the same results for the same input parameters; NOT DETERMINISTIC indicates that uncertain results are generated (default).
4 contains sql | no sql | reads sql data | modifies sql data Contains sql to indicate that the stored procedure contains statements for reading or writing data (default)
No sql means no sql statement
Reads sql data represents statements that stored procedures contain read-only data
Modifies sql data denotes that stored procedures contain statements that only write data
5 sql security: This feature specifies whether a stored procedure is executed with the permission of the user (definer) who created the stored procedure or with the permission of the invoker. Definition is Definer
Routine_body: The body of a stored procedure, which contains sql statements that must be executed when a procedure is called. Start with begin and end. If there is only one sql statement in the stored procedure body, the start-end flag can be omitted.
- CREATE TABLE
- t_user
- (
- USER_ID INT NOT NULL AUTO_INCREMENT,
- USER_NAME CHAR(30) NOT NULL,
- USER_PASSWORD CHAR(10) NOT NULL,
- USER_EMAIL CHAR(30) NOT NULL,
- PRIMARY KEY (USER_ID),
- INDEX IDX_NAME (USER_NAME)
- )
- ENGINE=InnoDB DEFAULT CHARSET=utf8;
(1) Storage process with IN
- //Create a stored procedure. Run in cmd
- CREATE PROCEDURE SP_SEARCH(IN p_name CHAR(20))
- BEGIN
- IF p_name is null or p_name='' THEN
- SELECT * FROM t_user;
- ELSE
- SELECT * FROM t_user WHERE USER_NAME LIKE p_name;
- END IF;
- END
As follows:
Call:
Result
- //Call and output the result.
- CALL SP_SEARCH('Pin-Wen Lin')
(2) Storage process with OUT
Invoke output: counting the number of people at the beginning of the forest
- //beltOUTReturn
- CREATE PROCEDURE SP_SEARCH2(IN p_name CHAR(20),OUT p_int INT)
- BEGIN
- IF p_name is null or p_name='' THEN
- SELECT * FROM t_user;
- ELSE
- SELECT * FROM t_user WHERE USER_NAME LIKE p_name;
- END IF;
- SELECT FOUND_ROWS() INTO p_int;
- END
- //Call and output the result.
- CALL SP_SEARCH2('Forest%',@p_num);
- SELECT @p_num;
(3) Storage process with INOUT
Output results:
- //Storage process with INOUT
- CREATE PROCEDURE sp_inout(INOUT p_num INT)
- BEGIN
- SET p_num=p_num*10;
- END
- //Call and output the result.
- SET @p_num=2;
- call sp_inout(@p_num);
- SELECT @p_num;
The combination of various sql statements and procedural statements can be used in stored procedure body to encapsulate complex business logic and processing rules in database application, so as to realize flexible programming of database application. Here are some common grammatical elements used to construct stored procedure bodies.
1. Local variables
Local variables can be declared in the stored procedure body to store temporary results in the stored procedure body.
Such as:
- DECLARE var_name[,...] type [DEFAULT value]
- Var_name:Specifies the name of a local variable
- Type:Data types used to declare local variables
- defaultclause:Used to specify a default value for a local variable. If not specified, default isnull.
Instructions:
- Declare cid int(10);
3. select... into statement
- Set var_name=expr
- Set cid=910;
Description: select in stored procedure body. The result set returned by the into statement can only have one row of data.
- Select col_name[,...] into var_name[,...] table_expr
- Col_name:Used to specify column names
- Var_name:The variable name used to specify the assignment
- Table_expr:ExpressselectIn the statementfromWords and sentences and the grammatical parts behind them
4. Defining Processing Procedures
It is a problem that may be encountered during the execution of pre-defined programs. And you can define solutions to these problems in the handler. This method can predict possible problems ahead of time and propose solutions.
5. Process Control Statement
- DECLARE handler_type HANDLER FOR condition_value[,...] sp_statement
- handler_type:CONTINUE | EXIT | UNDO
- Condition_value:Sqlwarning | not found | sqlexception
Search_condition parameter: conditional judgement statement
- If search_condition then statement_list
- [elseif search_condition then statement_list]...
- [else statement_list]
- End if
Storage process instance of multiple IF s
Data preparation
Student table:
- CREATE TABLE
- t_student
- (
- STU_ID INT NOT NULL,
- STU_NAME CHAR(10) NOT NULL,
- STU_CLASS INT NOT NULL,
- STU_SEX CHAR(2) NOT NULL,
- STU_AGE INT NOT NULL,
- PRIMARY KEY (STU_ID)
- )
- ENGINE=InnoDB DEFAULT CHARSET=utf8;
Score sheet (STU_ID is the student sheet is a foreign key relationship):
- CREATE TABLE
- t_grade
- (
- STU_ID INT NOT NULL,
- STU_SCORE INT NOT NULL,
- FOREIGN KEY (STU_ID) REFERENCES t_student (STU_ID),
- INDEX STU_ID (STU_ID)
- )
- ENGINE=InnoDB DEFAULT CHARSET=utf8;
Then write a stored procedure: the person who returns each score level
- //Storage Procedures with Multiple IF s
- CREATE PROCEDURE SP_SCHOLARSHIP_LEVEL(IN p_level char(1))
- BEGIN
- IF p_level ='A' THEN
- SELECT * FROM t_grade WHERE STU_SCORE >=90;
- ELSEIF p_level ='B' THEN
- SELECT * FROM t_grade WHERE STU_SCORE <90 AND STU_SCORE>=80;
- ELSEIF p_level ='C' THEN
- SELECT * FROM t_grade WHERE STU_SCORE <80 AND STU_SCORE>=70;
- ELSEIF p_level ='D' THEN
- SELECT * FROM t_grade WHERE STU_SCORE <60;
- ELSE
- SELECT * FROM t_grade;
- END IF;
- END
- //Call and output the result.
- CALL SP_SCHOLARSHIP_LEVEL('A');
Form 2
- Case case_value
- When when_value then statement_list
- [When when_value then statement_list]...
- [else statement_list]
- End case
Example
- Case
- When search_condition then statement_list
- End case
Call:
- CREATE PROCEDURE SP_SCHOLARSHIP_LEVEL3(IN p_level char(1))
- BEGIN
- DECLARE p_num int DEFAULT 0;
- CASE p_level
- WHEN 'A' THEN
- SET p_num=90;
- WHEN 'B' THEN
- SET p_num=80;
- WHEN 'C' THEN
- SET p_num=70;
- WHEN 'D' THEN
- SET p_num=60;
- ELSE
- SET p_num=0;
- END CASE;
- SELECT * FROM t_grade g, t_student s WHERE g.STU_ID=s.STU_ID AND g.STU_SCORE >= p_num ;
- END
- //Call and output the result.
- CALL SP_SCHOLARSHIP_LEVEL3('d');
(2) Loop statement
While statement, repeat statement and loop statement.
The While Statement
Judge whether the condition search_condition is true, if it is true, execute the statement in statement_list, and then judge, if it is still true, continue to loop until the condition judgement is not true.
- [begin_label:]
- while search_condition do
- Statement_list
- End while
- [end_label]
Output: Calculate 5!
- //Storage procedure with while
- CREATE PROCEDURE sp_cal(IN p_num INT,OUT p_result INT)
- BEGIN
- SET p_result=1;
- WHILE p_num > 1 DO
- SET p_result = p_num * p_result;
- SET p_num = p_num-1;
- END WHILE;
- END
- //Call and output the result.
- CALL sp_cal(5,@result);
- SELECT @result;
Repeat statement grammatical format
The Repeat statement first executes the statement in statement_list, and then determines whether the condition search_condition is true or not. If it is true, the loop ends and if it is not, the loop continues.
- [begin_label:]
- repeat
- Statement_list
- Until search_condition
- End repeat
- [end_label]
- //Storage process with repeat
- CREATE PROCEDURE sp_cal2(IN p_num INT,OUT p_result INT)
- BEGIN
- SET p_result=1;
- REPEAT
- SET p_result = p_num * p_result;
- SET p_num = p_num-1;
- UNTIL p_num<=1
- END REPEAT;
- END
- //Call and output the result.
- CALL sp_cal2(5,@result);
- SELECT @result;
- Call sp_name([parameter[,...]]);
- Sp_name Name of the called stored procedure
- Parameter:Specifies the parameters to be used to invoke stored procedures.
- Alter procedure proc_name[characteristic...]
- Drop procedure [if exists] sp_name;
In MySQL, the basic form of creating storage functions is as follows:
- CREATE FUNCTION sp_name([func_parameter[,...]])
- RETURNS type
- [characteristic ...] routine_body
- Return
The clause is used to declare the data type of the return value of the stored function. Stored procedure is a set of sql statements defined by users, involving tasks of specific tables or other objects. Users can call stored procedures. Functions are usually defined methods of the database, which receive parameters and return certain types of values without involving specific user tables.
Calling storage functions
Delete storage function drop
- Select sp_name([func_parameter...])
- Select fn_search(2);
(Compare sizes, return large numbers)
Call:
- /**Function usage**/
- CREATE FUNCTION sp_cal_max(p_num1 INT,p_num2 INT)
- RETURNS INT
- BEGIN
- IF p_num1 >= p_num2 THEN
- RETURN p_num1;
- ELSE
- RETURN p_num2;
- END IF;
- END
- SET @p_num1=2;
- SET @p_num2=34;
- SELECT sp_cal_max(@p_num1,@p_num2);
1) Generally speaking, the functions implemented by stored procedures are more complex, while the functions implemented by functions are more specific. Stored procedures, powerful, can perform a series of database operations including table modification; user-defined functions can not be used to perform a set of operations to modify the state of the global database.
2) For stored procedures, parameters, such as recordsets, can be returned, while functions can only return values or table objects. Functions can only return one variable; stored procedures can return more than one variable. The parameters of stored procedure can be IN, OUT and INOUT, while the function can only have IN class ~~stored procedure declaration without return type, while the function declaration needs to describe return type, and the function body must contain a valid RETURN statement.
3) Stored procedures can use uncertain functions, which are not allowed to be built in the body of user-defined functions.
4) Stored procedures are usually executed as a separate part (EXECUTE statement execution), while functions can be called as a part of the query statement (SELECT call), because functions can return a table object, so it can be placed behind the FROM keyword in the query statement. Stored procedures are not available in SQL statements, but functions can be used.
Query statements may query multiple records and use cursors in stored procedures and functions to read records in the query result set one by one. The use of cursors includes declaring the cursor, opening the cursor, using the cursor and closing the cursor. The cursor must declare the cursor, open the cursor, use the cursor, and close the cursor. The cursor must be declared before the handler and after variables and conditions.
1. Declare cursor
- Declare cursor_name cursor for select_statement;
- Cursor_name:Cursor name
- Select_statement:selectContent of statement
- Declare cur_employee cursor for select name,age from employee;
2. Open the cursor
- Open cursor_name
- Open cur_employee;
3. Use cursors
Mysql uses fetch keyword to use cursor, grammatical form
- Fetch cur_name intovar_name[,var_name...];
- Cur_name Represents the name of the cursor
- Var_name Represents that the cursor will be inselectThe information queried by the statement is stored in this parameter. Var_name It must be defined before the cursor is declared.
- Fetch cur_employee intoemp_name,emp_age;
4. Close the cursor
- Close cursor_name;
- Close cur_employee;
Each cursor should be closed when it is no longer needed, and using the close statement releases all the resources used by the cursor. When a cursor is closed, it cannot be used if it is not reopened. For declared cursors, you do not need to declare them again, but you can open them directly using the open statement.
(Copy table test_cur1 data to test_cur2)
Then write the cursor:
- CREATE TABLE `test_cur1` (
- `id` int(11) NOT NULL auto_increment,
- `type` char(11) default NULL,
- `order1` char(11) default NULL,
- PRIMARY KEY (`id`)
- )
- INSERT INTO `test_cur1` VALUES (1, '145', 'd1');
- INSERT INTO `test_cur1` VALUES (2, '134', '1d');
- INSERT INTO `test_cur1` VALUES (3, '123', '1ad');
- INSERT INTO `test_cur1` VALUES (4, '121', '1as');
- CREATE TABLE `test_cur2` (
- `id` int(11) NOT NULL auto_increment,
- `type` char(11) default NULL,
- `order1` char(11) default NULL,
- PRIMARY KEY (`id`)
- )
- create procedure get_cur ()
- BEGIN
- DECLARE done INT DEFAULT 0;
- DECLARE ID int(11);
- DECLARE type char(11);
- DECLARE order1 char(11);
- DECLARE mycur CURSOR FOR SELECT * FROM test_cur1;//Define cursor
- DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
- //Open the cursor.
- OPEN mycur;
- //Start the cycle.
- REPEAT
- FETCH mycur INTO ID,type,order1;//Remove cursor contents to temporary variables.
- IF NOT done THEN
- INSERT INTO test_cur2 VALUES (ID,type,order1);//Insert into another table
- END IF;
- UNTIL done END REPEAT;//End the loop when done=1
- //Close the cursor.
- CLOSE mycur;
- END
- call get_cur()
Indicates that the data has been successfully copied