MySQL stored procedures and triggers
Stored Procedures
First, a simple stored procedure
1, a simple stored procedure
$$ DELIMITER the Create Procedure Testa () the begin the Select * from emp; the Select * from the dept; End; $$; DELIMITER; - call a stored procedure call testa ();
Structure stored procedure consists of:
1, create a format: create procedure stored procedure name
2, between the begin and end comprising one or more code blocks, a code block using
3, create a need to define in the command line separator delimiter $$
2, the characteristics of the stored procedure
1, to complete the complex calculation and determination
2, programmable strong, flexible
3, SQL programming code may be reused
4, execution speed is relatively fast
5, to reduce the data transmission between the network, to save money
Second, the storage process variables
1, the process variables stored
Requirements: write stored procedures, use variables to take empno = username of 7369
$$ DELIMITER; the Create Procedure Testa (); the BEGIN the DECLARE my_uname VARCHAR (32) default ""; - defined variables my_uname the SET my_uname = 'Smith'; - variable assignment my_uname - empno = 7369 queries the user name and assign values to my_uname SELECT ename from my_uname INTO EMP WHERE EMPNO = 7369; - assigning a variable select my_uname; - my_uname return value of the END; $$; the Delimiter;
Features:
1, the variable declaration using declare, declare a just declare a variable, the variable must be declared before use.
2, having a variable data types and lengths, consistent with mysql SQL data types, but also to specify a default value, a character set and collation and the like.
3, variables can be assigned through the set, it can be assigned by select into fashion.
4, the variables need to return, you can use the select statement, such as: select the variable name
2, the process variable stored application example
Requirements: tables emp, dept and emp table of the number of rows in the earliest, the latest entry date.
Delimiter $$; Create procedure stats_emp(); BEGIN -- 统计emp和dept表中的记录数 BEGIN DECLARE emp_sum int default 0; DECLARE dept_sum int default 0; select count(*) into emp_sum from emp; select count(*) into dept_sum from dept; select emp_sum,dept_sum; END; -- 统计最早、最晚入职日期 BEGIN DECLARE max_time TIMESTAMP ; DECLARE min_time TIMESTAMP; select max(hiredate),min(hiredate) into max_time,min_time from emp; select max_time,min_time; END; END $$; Delimiter ;
Third, the stored procedure parameters
1, the stored procedure parameters passed IN
Requirements: write stored procedures, incoming empno, returned to the user's ename.
Delimiter $$; Create procedure test_param(IN my_empno int); -------- BEGIN DECLARE my_ename varchar(32) default ''; select ename into my_ename from emp where empno=my_empno; select my_ename; END; $$ Delimiter ; -- 调用 Call test_param(7369);
prompt:
1, passing parameters: type IN, represents the value of this parameter must be specified when calling a stored procedure, if you do not show designated as IN, then the default is IN type.
2, IN type parameter is generally used for incoming, call a stored procedure is generally not modified and returned.
3, if the need to modify the stored procedure call and return values may be used OUT type parameters.
2, stored procedure parameters outgoing OUT
Requirements: When calling a stored procedure, passing empno, returned to the user's ename.
Delimiter $$; create procedure test_param(IN my_empno int,OUT my_ename varcahr(32)); -------- BEGIN select ename into my_ename from emp where empno=my_empno; select my_ename; END; $$ Delimiter ; -- 调用 Set @uname=’’; Call test_param_out(7369,@uname);
prompt:
1, the outgoing parameters: call a stored procedure, you can change its value, and can be returned.
2, OUT is spread parameters, parameter values can not be used to pass.
3, when calling a stored procedure, OUT parameters also need to specify, but it must be a variable, not a constant.
4. If you need to pass both, at the same time requires outgoing, you can use INOUT type parameters.
3, the variable parameter stored procedure INOUT
Requirements: When calling a stored procedure parameters my_empno and my_ename, both incoming and also outgoing parameters.
Delimiter $$; create procedure test_param_inout(INOUT my_empno int,INOUT my_ename varchar(32)); BEGIN set my_empno=7369; set my_ename="smith"; select ename,empno into my_ename,my_empno from emp where empno=my_empno; END; $$ Delimiter ; -- 调用 set @uname:=''; set @empno:=7399; call test_param_inout(@empno,@uname); select @empno,@uname;
Features:
1, the variable INOUT variable, the value of the call can be passed, during the call, its value can be modified, but also can return a value.
2, INOUT parameter set function parameters of type IN and OUT
3, when an incoming call is INOUT variable rather than a constant
Fourth, the stored procedure conditional statements
1, conditional statement stored procedure
Requirements: Write a stored procedure, if the user is given empno is even ename, otherwise only return empno.
Delimiter $$; create procedure test_if(IN my_empno int); BEGIN DECLARE my_ename VARCHAR(32) default ''; if(my_empno %2=0) then select ename into my_ename from emp where empno=my_empno; select my_ename; else select my_empno; end if; END; $$ Delimiter ; -- 调用 call test_if(7369);
Features:
1, the basic structure of conditional statements: if () then ... else ... end if;
2, if the logic determines returns true or false, the expression may be any expression that returns true or false
2, conditional statements stored procedure application example
Requirements: according to the user's incoming empno parameter to determine:
(1) If the user sal is less than 2000, then the user to pay 200
(2) if the user sal less than 1000, to raise the user 500
(3) otherwise pay 100
Delimiter $$; create procedure test_if_else(IN my_empno int); BEGIN DECLARE my_sal int default 0; select sal into my_sal from emp where empno=my_empno; if(my_sal<1000) then update emp set sal=sal+500 where empno=my_empno; ELSEIF(my_sal<2000) then update emp set sal=sal+200 where empno=my_empno; else update emp set sal=sal+100 where empno=my_empno; end if; END; $$ Delimiter ; -- 调用 call test_if_else(7369);
Features:
Multi-conditional structure:
If()
Then
...
Else if()
Then
...
Else
...
End if;
Fifth, the stored procedure loop
1, while circulation
Demand: Use loop, 10 is inserted into consecutive recording empno emp table.
Delimiter $$; create procedure test_while(); BEGIN DECLARE i int default 0; while(i<10) DO BEGIN set i=i+1; insert into acc(id) values(i); END; END WHILE; END; $$ Delimiter ; -- 调用 call test_while();
Features:
1, while the basic sentence structure: while () do begin ... end end while ;;
2, while the logic determines returns true or false, the expression may be any expression that returns true or false
2, repeat loop
Demand: using a repeat loop acc insert 10 consecutive records to the table id
Delimiter $$; create procedure test_repeat(); BEGIN DECLARE i int default 100; REPEAT BEGIN set i=i+1; insert into acc(id) values(i); END; UNTIL i>=110 END REPEAT; END; $$ Delimiter ; -- 调用 call test_repeat();
Features:
1, repeat the basic sentence structure: repeat begin ... end until end repeat ;;
2, while the logic determines returns true or false, the expression may be any expression that returns true or false
Sixth, the stored procedure using a cursor
1. What are cursors
Requirements: write stored procedures, use the cursor, the uid is an even number of records one by one to update the user name.
$$ DELIMITER; Create Procedure test_cursor (); the BEGIN DECLARE the INT StopFlag the DEFAULT 0; - cursor stop flag 0: No Stop 1: Stopped DECLARE my_uname VARCHAR (32) default ' '; - a user name stored query DECLARE uname_cursor cURSOR for select uname from acc where uid% 2 = 0; - defining a cursor uname_cursor, and specify the result set DECLARE CONTINUE HANDLER for NOT found set stopflag = 1; - after the cursor is set to StopFlag. 1 open uname_cursor; - open cursor FETCH uname_cursor into my_uname; - - cursor step forward, taken in a record into my_uname my_uname the WHILE (StopFlag = 0) the DO the BEGIN Update the uname ACC SET = CONCAT (my_uname, "CUR _") WHERE the uname = my_uname; uname_cursor INTO my_uname the FETCH; the END; End the WHILE; Close uname_cursor; the END; $$ the Delimiter; - call call test_repeat ();
Features:
declare uname_cur Cursor for select uname from acc where uid%2=0;
1, the cursor is to save the query results temporary memory area
2, uname_cur cursor variable holds the provisional results of the query, the query result set is actually
Declare continue handler for not found set stopflag=1;
3, when the cursor variable holds the query results are again (traverse), reaches the end, the variable stopflag to 1.
4, FETCH uname_cursor into my_uname; - cursor step forward, taken in a record into my_uname
Mysql function
A, a simple function
Demand: Write function, passing a uid, returns the user's uname
Delimiter $$; CREATE FUNCTION f01_simple(my_uid int) RETURNS varchar(32) CHARSET utf8 BEGIN DECLARE my_uname varchar(32) default ''; select uname into my_uname from acc where uid=my_uid; RETURN my_uname; END $$ Delimiter ; -- 调用 Select f01_simple(2);
Features:
1, create a function using the create function function name (parameter) return return value
2, the function is placed between the begin and end member
3, return specified function return value
4, function calls: select function name (arguments);
Second, the custom function integrated application examples
1, exemplary custom function 01
Demand: Enter the user UID, uuid value obtained accountid, uid, uname combination, as the user's unique identification.
Delimiter $$; CREATE FUNCTION test_uuid(my_uid int) RETURNS varchar(32) CHARSET utf8 BEGIN DECLARE uuid varchar(32) default ''; select CONCAT(accountid,"_",uid,"_",uname) INTO uuid from acc where uid=my_uid; RETURN uuid; END $$; Delimiter ; -- 调用 Select test_uuid(2);
2, exemplary custom function 02
Requirements: Enter the user uid, uid to calculate the total price for all orders under where the accounts.
Trigger trigger
Scene: In general for auditing, business data integrity
1, what is the trigger
Demand: in auditing purposes, when someone inserts a record into table users, the insertion uid, uname operation and the operation time and recorded.
$$ DELIMITER; the CREATE TRIGGER `` tr_users_insert` an AFTER the INSERT the ON users` the FOR EACH the ROW the BEGIN - New inserted after the current user information insert into oplog (uid, uname, action, optime) VALUES (NEW.uid, NEW.uname, 'INSERT', now ()); the END; $$; the Delimiter;
Features:
1, create triggers using create trigger trigger name.
2, when the trigger? after insert on users, as well as after treatment before, is after (before) or (after) the table before the operation trigger action pair.
3, the operation of what event triggers? After insert on users, the operation time including insert, update, delete
4, triggering what table? after insert on users
5, the impact of scope? For each row
Trigger: with functions, stored procedures, as trigger is an object that can operate according to the event on the table, triggering a number of actions that can be insert, update, delete and other modification operations.
2, production examples of the flip-flop
Requirements: in auditing purposes, when users delete the table, record the main field value of the record before deleting.
Delimiter $$; CREATE TRIGGER `tr_user_delete` BEFORE DELETE ON `users` FOR EACH ROW begin -- OLD对字段表更新前的数据 insert into oplog(uid,uname,action,optime,old_value) values(OLD.uid,OLD.uname,"delete",now(),OLD.regtime); END; $$; Delimiter ;