1. Trigger:
Create trigger trigger_name trigger_time trigger_event ON tbl_name for each row trigger_stmt
Trigger_name indicates the trigger name, which is specified by the user; trigger_time indicates the trigger time, which is replaced by before and after; trigger_event indicates the trigger event, which is replaced by insert, updat e, and delete; bl_name indicates the name of the table on which the trigger is created. trigger_stmt indicates the trigger program body. The trigger program can use begin and end as the start and end, with multiple statements in the middle;
There are several status maps and several Wei tables:
Insert: NEW
Update: NEW OLD
Delete: OLD
Status: Indicates whether new data and old data exist.
2. In Process
1. mysql> DELIMITER //
2. mysql> create procedure proc1 (OUT s int)
3.-> BEGIN
4.-> select count (*) INTO s FROM user;
5.-> END
6.-> //
7. mysql> DELIMITER;
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:
Create procedure ([[IN | OUT | INOUT] Parameter Name Data class...])
IN input parameter: 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 parameter: The value can be changed within the stored procedure and can be returned.
INOUT input and output parameters: this parameter is specified during the call and can be changed or returned.
I. IN parameter example
Create:
1. mysql> DELIMITER //
2. mysql> create procedure demo_in_parameter (IN p_in int)
3.-> BEGIN
4.-> SELECT p_in;
5.-> SET p_in = 2;
6.-> SELECT p_in;
7.-> END;
8.-> //
9. mysql> DELIMITER;
Execution result:
1. mysql> SET @ p_in = 1;
2. mysql> CALL demo_in_parameter (@ p_in );
3. + ------ +
4. | p_in |
5. + ------ +
6. | 1 |
7. + ------ +
8.
9. + ------ +
10. | p_in |
11. + ------ +
12. | 2 |
13. + ------ +
14.
15. mysql> SELECT @ p_in;
16. + ------- +
17. | @ p_in |
18. + ------- +
19. | 1 |
20. + ------- +
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
Create:
1. mysql> DELIMITER //
2. mysql> create procedure demo_out_parameter (OUT p_out int)
3.-> BEGIN
4.-> SELECT p_out;
5.-> SET p_out = 2;
6.-> SELECT p_out;
7.-> END;
8.-> //
9. mysql> DELIMITER;
Execution result:
1. mysql> SET @ p_out = 1;
2. mysql> CALL sp_demo_out_parameter (@ p_out );
3. + ------- +
4. | p_out |
5. + ------- +
6. | NULL |
7. + ------- +
8.
9. + ------- +
10. | p_out |
11. + ------- +
12. | 2 |
13. + ------- +
14.
15. mysql> SELECT @ p_out;
16. + ------- +
17. | p_out |
18. + ------- +
19. | 2 |
20. + ------- +
Iii. Example of INOUT Parameters
Create:
1. mysql> DELIMITER //
2. mysql> create procedure demo_inout_parameter (INOUT p_inout int)
3.-> BEGIN
4.-> SELECT p_inout;
5.-> SET p_inout = 2;
6.-> SELECT p_inout;
7.-> END;
8.-> //
9. mysql> DELIMITER;
Execution result:
1. mysql> SET @ p_inout = 1;
2. mysql> CALL demo_inout_parameter (@ p_inout );
3. + --------- +
4. | p_inout |
5. + --------- +
6. | 1 |
7. + --------- +
8.
9. + --------- +
10. | p_inout |
11. + --------- +
12. | 2 |
13. + --------- +
14.
15. mysql> SELECT @ p_inout;
16. + ---------- +
17. | @ p_inout |
18. + ---------- +
19. | 2 |
20. + ---------- +
(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:
1. DECLARE l_int int unsigned default 4000000;
2. DECLARE l_numeric number (9.95) DEFAULT;
3. DECLARE l_date date DEFAULT '2017-12-31 ';
4. DECLARE l_datetime datetime DEFAULT '2017-12-31 23:59:59 ';
5. 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
1. mysql> SELECT 'Hello world' into @ x;
2. mysql> SELECT @ x;
3. + ------------- +
4. | @ x |
5. + ------------- +
6. | Hello World |
7. + ------------- +
8. mysql> SET @ y = 'Goodbye Cruel world ';
9. mysql> SELECT @ y;
10. + --------------------- +
11. | @ y |
12. + --------------------- +
13. | Goodbye Cruel World |
14. + --------------------- +
15.
16. mysql> SET @ z = 1 + 2 + 3;
17. mysql> SELECT @ z;
18. + ------ +
19. | @ z |
20. + ------ +
21. | 6 |
22. + ------ +
Ii. Use user variables in Stored Procedures
1. mysql> create procedure GreetWorld () select concat (@ greeting, 'World ');
2. mysql> SET @ greeting = 'hello ';
3. mysql> CALL GreetWorld ();
4. + ---------------------------- +
5. | CONCAT (@ greeting, 'World') |
6. + ---------------------------- +
7. | Hello World |
8. + ---------------------------- +
Iii. Pass global user variables between stored procedures
1. mysql> create procedure p1 () SET @ last_procedure = 'p1 ';
2. mysql> create procedure p2 () select concat ('Last procedure was', @ last_proc );
3. mysql> CALL p1 ();
4. mysql> CALL p2 ();
5. + ------------------------------------------------- +
6. | CONCAT ('Last procedure was', @ last_proc |
7. + ------------------------------------------------- +
8. | Last procedure was p1 |
9. + ------------------------------------------------- +
Note:
① 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:
1. mysql> DELIMITER //
2. mysql> create procedure proc1 -- name stored PROCEDURE name
3.-> (IN parameter1 INTEGER)
4.-> BEGIN
5.-> DECLARE variable1 CHAR (10 );
6.-> IF parameter1 = 17 THEN
7.-> SET variable1 = 'birds ';
8.-> ELSE
9.-> SET variable1 = 'beasts ';
10.-> end if;
11.-> insert into table1 VALUES (variable1 );
12.-> END
13.-> //
14. mysql> DELIMITER;
4. MySQL stored 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. query MySQL stored procedures
As we know the tables under a database, we generally use show tables; 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 name from mysql. proc where db = 'database name ';
Or
Select routine_name from information_schema.routines where routine_schema = 'database name ';
Or
Show procedure status 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 create procedure database. Name of the stored PROCEDURE;
You can view the details of the current stored procedure.
6. Modify the MySQL Stored Procedure
ALTER PROCEDURE
Change the pre-specified stored PROCEDURE created with create procedure without affecting the stored PROCEDURE or function.
7. Delete the MySQL Stored Procedure
Deleting a stored procedure is simple, just like deleting a table:
DROP PROCEDURE
Delete one or more stored procedures from a MySQL table.
8. MySQL stored 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.
1. mysql> DELIMITER //
2. mysql> create procedure proc3 ()
3.-> begin
4.-> declare x1 varchar (5) default 'outer ';
5.-> begin
6.-> declare x1 varchar (5) default 'inner ';
7.-> select x1;
8.-> end;
9.-> select x1;
10.-> end;
11.-> //
12. mysql> DELIMITER;
(2). Condition Statement
I. if-then-else statement
1. mysql> DELIMITER //
2. mysql> create procedure proc2 (IN parameter int)
3.-> begin
4.-> declare var int;
5.-> set var = parameter + 1;
6.-> if var = 0 then
7.-> insert into t values (17 );
8.-> end if;
9.-> if parameter = 0 then
10.-> update t set s1 = s1 + 1;
11.-> else
12.-> update t set s1 = s1 + 2;
13.-> end if;
14.-> end;
15.-> //
16. mysql> DELIMITER;
Ii. case statement:
1. mysql> DELIMITER //
2. mysql> create procedure proc3 (in parameter int)
3.-> begin
4.-> declare var int;
5.-> set var = parameter + 1;
6.-> case var
7.-> when 0 then
8.-> insert into t values (17 );
9.-> when 1 then
10.-> insert into t values (18 );
11.-> else
12.-> insert into t values (19 );
13.-> end case;
14.-> end;
15.-> //
16. mysql> DELIMITER;
(3). Loop statement
I. while... end while:
1. mysql> DELIMITER //
2. mysql> create procedure proc4 ()
3.-> begin
4.-> declare var int;
5.-> set var = 0;
6.-> while var <6 do
7.-> insert into t values (var );
8.-> set var = var + 1;
9.-> end while;
10.-> end;
11.-> //
12. mysql> DELIMITER;
Ii. repeat · end repeat:
It checks the result after the operation is executed, while it checks before the execution.
1. mysql> DELIMITER //
2. mysql> create procedure proc5 ()
3.-> begin
4.-> declare v int;
5.-> set v = 0;
6.-> repeat
7.-> insert into t values (v );
8.-> set v = v + 1;
9.-> until v> = 5
10.-> end repeat;
11.-> end;
12.-> //
13. mysql> DELIMITER;
Iii. loop · end loop:
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.
1. mysql> DELIMITER //
2. mysql> create procedure proc6 ()
3.-> begin
4.-> declare v int;
5.-> set v = 0;
6.-> LOOP_LABLE: loop
7.-> insert into t values (v );
8.-> set v = v + 1;
9.-> if v> = 5 then
10.-> leave LOOP_LABLE;
11.-> end if;
12.-> end loop;
13.-> end;
14.-> //
15. 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
I. ITERATE:
Reference the compound statement label to start a compound statement.
1. mysql> DELIMITER //
2. mysql> create procedure proc10 ()
3.-> begin
4.-> declare v int;
5.-> set v = 0;
6.-> LOOP_LABLE: loop
7.-> if v = 3 then
8.-> set v = v + 1;
9.-> ITERATE LOOP_LABLE;
10.-> end if;
11.-> insert into t values (v );
12.-> set v = v + 1;
13.-> if v> = 5 then
14.-> leave LOOP_LABLE;
15.-> end if;
16.-> end loop;
17.-> end;
18.-> //
19. mysql> DELIMITER;
9. basic functions of the MySQL Stored Procedure
(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.
1. mysql> select substring ('abcd );
2. + ----------------------- +
3. | substring ('abcd',) |
4. + ----------------------- +
5. |
6. + ----------------------- +
7.1 row in set (0.00 sec)
8.
9. mysql> select substring ('abcd', 1, 2 );
10. + ----------------------- +
11. | substring ('abcd', 1, 2) |
12. + ----------------------- +
13. | AB |
14. + ----------------------- +
15.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.
1. mysql> select round (1.23 );
2. + ------------- +
3. | round (1.23) |
4. + ------------- +
5. | 1 |
6. + ------------- +
7.1 row in set (0.00 sec)
8.
9. mysql> select round (1.56 );
10. + ------------- +
11 .. | round (1.56) |
12. + ------------- +
13. | 2 |
14. + ------------- +
15.1 row in set (0.00 sec)
(2) the number of decimal places can be set to return floating point data.
1. mysql> select round (1.567, 2 );
2. + ---------------- +
3. | round (1.567, 2) |
4. + ---------------- +
5. | 1.57 |
6. + ---------------- +
7.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
MICROSECOND (datetime) // MICROSECOND
MONTH (datetime) // MONTH
MINUTE (datetime) // return the MINUTE sign, positive or negative or 0
SQRT (number2) // Square