search
HomeDatabaseMysql Tutorialmysql 触发器 进程

mysql 触发器 进程

Jun 07, 2016 pm 04:26 PM
mysqltriggerprocessprocess

mysql 触发器 过程 1、触发器: CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt 其中trigger_name标识触发器名称,用户自行指定; trigger_time标识触发时机,用before和after替换; trigger_event标识触发

mysql 触发器 过程

1、触发器:

CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt
其中trigger_name标识触发器名称,用户自行指定;trigger_time标识触发时机,用before和after替换;trigger_event标识触发事件,用insert,updat e和delete替换;bl_name标识建立触发器的表名,即在哪张表上建立触发器;trigger_stmt是触发器程序体;触发器程序可以使用begin和end作为开 始和结束,中间包含多条语句;

有几个状态对像和几张伟表:

insert : NEW

update : NEW OLD

delete : OLD

status  : 表示是否有新数据和老数据


2、过程中

   

  1. mysql> DELIMITER //  
  2. mysql> CREATE PROCEDURE proc1(OUT int)  
  3.     -> BEGIN 
  4.     -> SELECT COUNT(*) INTO FROM user;  
  5.     -> END 
  6.     -> //  
  7. mysql> DELIMITER 

MySQL存储过程的参数用在存储过程的定义,共有三种参数类型,IN,OUT,INOUT,形式如:

CREATE PROCEDURE([[IN |OUT |INOUT ] 参数名 数据类形...])

IN 输入参数:表示该参数的值必须在调用存储过程时指定,在存储过程中修改该参数的值不能被返回,为默认值

OUT 输出参数:该值可在存储过程内部被改变,并可返回

INOUT 输入输出参数:调用时指定,并且可被改变和返回

. IN参数例子

创建:

  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 


执行结果
:

  1. mysql SET @p_in=1;  
  2. mysql CALL demo_in_parameter(@p_in);  
  3. +------+  
  4. p_in |  
  5. +------+  
  6.      
  7. +------+  
  8.  
  9. +------+  
  10. p_in |  
  11. +------+  
  12.      
  13. +------+  
  14.  
  15. mysql> SELECT @p_in;  
  16. +-------+  
  17. @p_in |  
  18. +-------+  
  19.     |  
  20. +-------+  


以上可以看出,
p_in虽然在存储过程中被修改,但并不影响@p_id的值

 

.OUT参数例子

创建:

  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 


执行结果
:

  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.       
  13. +-------+  
  14.  
  15. mysql> SELECT @p_out;  
  16. +-------+  
  17. p_out |  
  18. +-------+  
  19.     |  
  20. +-------+  


. INOUT参数例子

创建:

  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 

 

 

执行结果:
  1. mysql > SET @p_inout=1;  
  2. mysql > CALL demo_inout_parameter(@p_inout) ;  
  3. +---------+  
  4. p_inout |  
  5. +---------+  
  6.       |  
  7. +---------+  
  8.  
  9. +---------+  
  10. p_inout   
  11. +---------+  
  12.       |  
  13. +---------+  
  14.  
  15. mysql > SELECT @p_inout;  
  16. +----------+  
  17. @p_inout   
  18. +----------+  
  19.        |  
  20. +----------+ 

(4). 变量

. 变量定义

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

其中,datatypeMySQL的数据类型,如:int, float, date, varchar(length)

例如:

  1. DECLARE l_int int unsigned default 4000000;  
  2. DECLARE l_numeric number(8,2) DEFAULT 9.95;  
  3. DECLARE l_date date DEFAULT '1999-12-31';  
  4. DECLARE l_datetime datetime DEFAULT '1999-12-31 23:59:59';  
  5. DECLARE l_varchar varchar(255) DEFAULT 'This will not be padded'  

 

 

. 变量赋值

 SET 变量名 = 表达式值 [,variable_name = expression ...]

 

. 用户变量

 

. MySQL客户端使用用户变量

  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.    |  
  22. +------+  

ⅱ. 在存储过程中使用用户变量

  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. +----------------------------+  

 

. 在存储过程间传递全局范围的用户变量
  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. +-----------------------------------------------+  

 

 

注意:

用户变量名一般以@开头

滥用用户变量会导致程序难以理解及管理

 

(5). 注释

 

MySQL存储过程可使用两种风格的注释

双模杠:--

该风格一般用于单行注释

c风格: 一般用于多行注释

例如:

 

  1. mysql DELIMITER //  
  2. mysql CREATE PROCEDURE proc1 --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存储过程的调用

call和你过程名以及一个括号,括号里面根据需要,加入参数,参数包括输入参数、输出参数、输入输出参数。具体的调用方法可以参看上面的例子。

5.      MySQL存储过程的查询

我们像知道一个数据库下面有那些表,我们一般采用show tables;进行查看。那么我们要查看某个数据库下面的存储过程,是否也可以采用呢?答案是,我们可以查看某个数据库下面的存储过程,但是是令一钟方式。

我们可以用

select name from mysql.proc where db=’数据库名’;

或者

select routine_name from information_schema.routines where routine_schema='数据库名';

或者

show procedure status where db='数据库';

进行查询。

如果我们想知道,某个存储过程的详细,那我们又该怎么做呢?是不是也可以像操作表一样用describe 表名进行查看呢?

答案是:我们可以查看存储过程的详细,但是需要用另一种方法:

SHOW CREATE PROCEDURE 数据库.存储过程名;

就可以查看当前存储过程的详细。

 

6.      MySQL存储过程的修改

ALTER PROCEDURE

更改用CREATE PROCEDURE 建立的预先指定的存储过程,其不会影响相关存储过程或存储功能。

 

7.      MySQL存储过程的删除

删除一个存储过程比较简单,和删除表一样:

DROP PROCEDURE

MySQL的表格中删除一个或多个存储过程。

 

8.      MySQL存储过程的控制语句

(1). 变量作用域

内部的变量在其作用域范围内享有更高的优先权,当执行到end。变量时,内部变量消失,此时已经在其作用域外,变量不再可见了,应为在存储
过程外再也不能找到这个申明的变量,但是你可以通过out参数或者将其值指派
给会话变量来保存其值。

 

 

  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). 条件语句

. if-then -else语句

 

 

 

  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 values(17);  
  8.      -> end if;  
  9.      -> if parameter=0 then 
  10.      -> update set s1=s1+1;  
  11.      -> else 
  12.      -> update set s1=s1+2;  
  13.      -> end if;  
  14.      -> end;  
  15.      -> //  
  16. mysql DELIMITER ;  


. case语句: 

  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 then   
  8.      -> insert into values(17);  
  9.      -> when then   
  10.      -> insert into values(18);  
  11.      -> else   
  12.      -> insert into values(19);  
  13.      -> end case;  
  14.      -> end;  
  15.      -> //  
  16. mysql DELIMITER 

 

(3). 循环语句

. while ···· end while

  1. mysql DELIMITER //  
  2. mysql CREATE PROCEDURE proc4()  
  3.      -> begin 
  4.      -> declare var int;  
  5.      -> set var=0;  
  6.      -> while vardo  
  7.      -> insert into values(var);  
  8.      -> set var=var+1;  
  9.      -> end while;  
  10.      -> end;  
  11.      -> //  
  12. mysql DELIMITER 

 

 

. repeat···· end repeat

它在执行操作后检查结果,而while则是执行前进行检查。

  1. mysql DELIMITER //  
  2. mysql CREATE PROCEDURE proc5 ()  
  3.      -> begin   
  4.      -> declare int;  
  5.      -> set v=0;  
  6.      -> repeat  
  7.      -> insert into values(v);  
  8.      -> set v=v+1;  
  9.      -> until v>=5  
  10.      -> end repeat;  
  11.      -> end;  
  12.      -> //  
  13. mysql DELIMITER ;  

 


. loop ·····end loop:

loop循环不需要初始条件,这点和while 循环相似,同时和repeat循环一样不需要结束条件, leave语句的意义是离开循环。

  1. mysql DELIMITER //  
  2. mysql CREATE PROCEDURE proc6 ()  
  3.      -> begin 
  4.      -> declare int;  
  5.      -> set v=0;  
  6.      -> LOOP_LABLE:loop  
  7.      -> insert into values(v);  
  8.      -> set v=v+1;  
  9.      -> if >=5 then 
  10.      -> leave LOOP_LABLE;  
  11.      -> end if;  
  12.      -> end loop;  
  13.      -> end;  
  14.      -> //  
  15. mysql DELIMITER ;  

 

 

. LABLES 标号:

标号可以用在begin repeat while 或者loop 语句前,语句标号只能在合法的语句前面使用。可以跳出循环,使运行指令达到复合语句的最后一步。

 

(4). ITERATE迭代

. ITERATE:

通过引用复合语句的标号,来从新开始复合语句

  1. mysql DELIMITER //  
  2. mysql CREATE PROCEDURE proc10 ()  
  3.      -> begin 
  4.      -> declare 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 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.      MySQL存储过程的基本函数

 

(1).字符串类

CHARSET(str) //返回字串字符集
CONCAT (string2 [,... ]) //
连接字串
INSTR (string ,substring ) //
返回substring首次在string中出现的位置,不存在返回0
LCASE (string2 ) //
转换成小写

LEFT (string2 ,length ) //
string2中的左边起取length个字符
LENGTH (string ) //string
长度
LOAD_FILE (file_name ) //
从文件读取内容
LOCATE (substring , string [,start_position ] )
 INSTR,但可指定开始位置
LPAD (string2 ,length ,pad ) //
重复用pad加在string开头,直到字串长度为length
LTRIM (string2 ) //
去除前端空格

REPEAT (string2 ,count ) //
重复count
REPLACE (str ,search_str ,replace_str ) //
str中用replace_str替换search_str
RPAD (string2 ,length ,pad) //
str后用pad补充,直到长度为
length
RTRIM (string2 ) //
去除后端空格

STRCMP (string1 ,string2 ) //
逐字符比较两字串大小,
SUBSTRING (str , position [,length ]) //
strposition开始,length个字符
,
注:mysql中处理字符串时,默认第一个字符下标为1,即参数position必须大于等于1
 

 

  1. mysql> select substring('abcd',0,2);  
  2. +-----------------------+  
  3. substring('abcd',0,2) |  
  4. +-----------------------+  
  5.                       |  
  6. +-----------------------+  
  7. 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. row in set (0.02 sec)  

TRIM([[BOTH|LEADING|TRAILING] [padding] FROM]string2) //去除指定位置的指定字符
UCASE (string2 ) //
转换成大写
RIGHT(string2,length) //
string2最后length个字符
SPACE(count) //
生成count个空格

(2).数学类

ABS (number2 ) //绝对值
BIN (decimal_number ) //
十进制转二进制
CEILING (number2 ) //
向上取整
CONV(number2,from_base,to_base) //
进制转换
FLOOR (number2 ) //
向下取整
FORMAT (number,decimal_places ) //
保留小数位数
HEX (DecimalNumber ) //
转十六进制
注:HEX()中可传入字符串,则返回其ASC-11,如HEX('DEF')返回4142143
也可以传入十进制整数,返回其十六进制编码,如HEX(25)返回
19
LEAST (number , number2 [,..]) //
求最小值

MOD (numerator ,denominator ) //
求余
POWER (number ,power ) //
求指数
RAND([seed]) //
随机数
ROUND (number [,decimals ]) //
四舍五入,decimals为小数位数]

注:返回类型并非均为整数,如:
(1)
默认变为整形值

  1. mysql> select round(1.23);  
  2. +-------------+  
  3. round(1.23) |  
  4. +-------------+  
  5.           |  
  6. +-------------+  
  7. row in set (0.00 sec)  
  8.  
  9. mysql> select round(1.56);  
  10. +-------------+  
  11. round(1.56) |  
  12. +-------------+  
  13.           |  
  14. +-------------+  
  15. row in set (0.00 sec) 



(2)
可以设定小数位数,返回浮点型数据

  1. mysql> select round(1.567,2);  
  2. +----------------+  
  3. round(1.567,2) |  
  4. +----------------+  
  5.           1.57 |  
  6. +----------------+  
  7. row in set (0.00 sec) 

SIGN (number2 ) //

 

(3).日期时间类

ADDTIME (date2 ,time_interval ) //time_interval加到date2
CONVERT_TZ (datetime2 ,fromTZ ,toTZ ) //
转换时区
CURRENT_DATE ( ) //
当前日期
CURRENT_TIME ( ) //
当前时间
CURRENT_TIMESTAMP ( ) //
当前时间戳
DATE (datetime ) //
返回datetime的日期部分
DATE_ADD (date2 , INTERVAL d_value d_type ) //
date2中加上日期或时间
DATE_FORMAT (datetime ,FormatCodes ) //
使用formatcodes格式显示datetime
DATE_SUB (date2 , INTERVAL d_value d_type ) //
date2上减去一个时间
DATEDIFF (date1 ,date2 ) //
两个日期差
DAY (date ) //
返回日期的天
DAYNAME (date ) //
英文星期
DAYOFWEEK (date ) //
星期(1-7) ,1为星期天
DAYOFYEAR (date ) //
一年中的第几天
EXTRACT (interval_name FROM date ) //
date中提取日期的指定部分
MAKEDATE (year ,day ) //
给出年及年中的第几天,生成日期串
MAKETIME (hour ,minute ,second ) //
生成时间串
MONTHNAME (date ) //
英文月份名
NOW ( ) //
当前时间
SEC_TO_TIME (seconds ) //
秒数转成时间
STR_TO_DATE (string ,format ) //
字串转成时间,format格式显示
TIMEDIFF (datetime1 ,datetime2 ) //
两个时间差
TIME_TO_SEC (time ) //
时间转秒数]
WEEK (date_time [,start_of_week ]) //
第几周
YEAR (datetime ) //
年份
DAYOFMONTH(datetime) //
月的第几天
HOUR(datetime) //
小时
LAST_DAY(date) //date
的月的最后日期
MICROSECOND(datetime) //
微秒
MONTH(datetime) //

MINUTE(datetime) //
返回符号,正负或0
SQRT(number2) //
开平方









Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.