当前位置:网站首页>MySQL stored procedure study notes (based on 8.0)
MySQL stored procedure study notes (based on 8.0)
2022-08-04 06:43:00 【Louzen】
官方文档:https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
MySQL存储过程语法(基于8.0)
/*存储过程 & 方法 的定义:*/
CREATE
[DEFINER = user]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
CREATE
[DEFINER = user]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic: {
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
}
routine_body:
Valid SQL routine statement
官方文档翻译
- 存储过程、methods will be defined for the default database,If you want to specify the database, you need to definedb_name.sp_name
- Loadable methods can be treated as stored procedures
- Stored procedure is to be called,call it in an expression,and the stored procedure has a return value
- Creating a stored procedure or method requires permission,如果存在DEFINER语句
- (https://dev.mysql.com/doc/refman/8.0/en/stored-objects-security.html),then permissions depend onDEFINER中的user,If you need to open the binary log requires super authority
- 默认的,MySQLAutomatically agrees that the creator owns the modification to the stored procedure or method、执行权限,This default consent can be set by the system parameterautomatic_sp_privileges所改变
- DEFINER和SQLThe security clause specifies the security context to use when checking access rights at routine execution time(直译,不太理解)
- Try to avoid the stored procedure、方法名与MySQLBuilt-in built-in methods are renamed,如果重名,please define、When executing the stored procedure、Add a space between the method name and the following parentheses.whitespace ignoredSQL语法只对MySQLThe built-in method works,and not valid for stored procedures,stored procedure name,无论IGNORE_SPACEAre the parameters valid?,You can add a space after the stored procedure name
- The parameter list in parentheses must always exist,Even if there are no parameters, there should be an empty pair of parentheses in the parameter position,参数名不区分大小写
- By default the parameters of the stored procedure areIN,To specify a different value for the parameter,Please use keyword before parameter nameOUT或INOUT,注意,Only the parameters of the stored procedure are distinguishedIN、OUT、INOUT,The parameters in the method definition areIN
- 存储过程INParameters can be changed during the process,But the caller of the stored procedure will not notice the change(类似于java中的传值),OUT参数初始值为null,OUTThe value is returned to the caller after the stored procedure ends,INOUTValues are before introduced into a stored procedure is called an initial value,Then assign the new value during the execution of the stored procedure,Finally, the end of the execution returns the new value to the caller
- 因为OUT或INOUTThe parameter will return the value after the stored procedure has finished running,We can call a stored procedure in other stored procedure or method,OUT或INOUTParameters can be parameters of the outer stored procedure or method、自定义的变量、表中的一列
- If the stored procedure throws an unhandled exception,则OUT和INOUTThe value of the parameter is not passed back to the caller.If the exception is contained byRESIGNAL语句的CONTINUE或EXIT处理程序处理,RESIGNALThe execution of the diagnostic area will pop up the stack,to signal an exception(i.e. information that existed before entering the handler).if the exception is an error,则OUT和INOUTThe value of the parameter is not passed back to the caller.
- Routine parameters cannot be referenced in prepared statements within a routine(暂时不理解,keep looking back)
- Parameter types and function return types can be declared to use any valid data type.If preceded by a character set specification,则可以使用COLLATE属性(直译,I don't understand the last sentence)
- Inside the code body of the stored procedure(BEGIN和END之间的部分)可以写简单的SQL语句比如select、insert,You can also write compound statements,Compound statement can contain life、循环和其他控制结构语句,语法遵循:https://dev.mysql.com/doc/refman/8.0/en/sql-compound-statements.html,实际上,Stored methods tend to use compound statements rather than just a singlereturn语句
- MySQLAllow code body to containDDL(数据库定义语言),比如create和drop,MySQLStored procedures are also allowed(Not a way to store)包含SQLTransaction statements such ascommit,Stored methods cannot contain statements that perform an explicit or implicit commit or rollback.SQLThe standard does not require support for these statements,The standard specifies that eachDBMSVendors can decide whether to allow them.DBMS:数据库管理软件(Data Base Management Software)or database management system(Data Base Management System)
- Statements that return result sets can be used in stored procedures,But the storage method cannot,This prohibition includes noINTO var_list语句的select语句,也包括show、explain、check table语句,Writing this statement when the method is defined will report“return result set is not allowed”的错误(ER_SP_NO_RETSET,https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html#error_er_sp_no_retset),In the run-time storage method, the method that returns the result set will report“A result set cannot be returned in the given context”错误(ER_SP_BADSELECT,https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html#error_er_sp_badselect)
- Stored procedures are not alloweduse语句,When a stored procedure runs,use db_namestatement will run implicitly(Because the front of the stored procedure must be belong to a library has said)and undo after the process execution ends.make the routine execute with the given default database,References to objects in the database other than the routine default database should be qualified with the appropriate database name(我自己的理解,Stored procedures belong to a database by default,In the stored procedure, use the table in the default library directly with the name of the table,Use tables from other libraries to“库.表明”这样用)
- More on Statements Not Allowed in Stored Routines:https://dev.mysql.com/doc/refman/8.0/en/stored-program-restrictions.html
- about usingMySQLInformation about calling stored procedures in programs written in the interface language,请参阅:https://dev.mysql.com/doc/refman/8.0/en/call.html
- MySQLSave the stored procedure when it is created or modifiedsql_modeSystem variables and take effect,This variable is always used to execute the stored procedure later.,ignore current serverSQL mode是多少
- from the calling programSQLMode switch to routine'sSQLMode occurs after parameter evaluation and assignment of the resulting value to the routine parameter.(不理解)
- COMMENT 特性是MySQL扩展,Can be used to describe stored routines,
show create procedure:https://dev.mysql.com/doc/refman/8.0/en/show-create-procedure.html;
show create function:https://dev.mysql.com/doc/refman/8.0/en/show-create-function.html - LANGUAGE Attribute represents the language in which the routine is written.The server ignores this feature;仅支持SQL例程
- If a routine always produces the same result for the same input parameters,then it is considered to be“确定的 deterministic”,Otherwise it is considered to be“不确定的 not deterministic”.If neither is given in the routine definition DETERMINISTIC 也没有给出 NOT DETERMINISTIC ,则默认为 NOT DETERMINISTIC.To declare a function to be deterministic,必须显式指定 DETERMINISTIC
- The determination of the nature of the routine depends on the creator's“诚实”:MySQLwill not check being declared as“确定的”Does the routine contain statements that produce indeterminate results.然而,Incorrectly declaring a routine may affect results or performance,declares an indeterminate routine as“确定 DETERMINISTIC”May lead to unknown results by causing the optimizer to choose the wrong execution count;Declare a definite routine as“不确定 NONDETERMINISTIC”May degrade performance due to not using optimizations
- If binary logging is enabled,“确定 DETERMINISTIC”特征影响MySQLAccepted routine definitions(不理解)
- 包含NOW()函数(或其同义词)或RAND()The routine is undefined,But it may still be copy-safe.对于NOW()函数,Binary logs contain timestamps and are copied correctly;RAND()also reproduces correctly,As long as the function is called only once in the routine.We can see that when copying,The same timestamp and random number are used to generate the seed when executing both methods in the source and replica,This will make the replica copied through the binary file consistent with the source data
- Several properties provide information on the nature of the data used by the routine(不理解),在MySQLThese features are advisory,The server does not use them to constrain which statements the routine is allowed to execute.
- CONTAINS SQL Indicates that the routine does not contain statements to read or write data,If these properties are not explicitly given then this is the default.比如有语句:"SET @X = 1"或"DO RELEASE_LOCK(‘abc’)"These statements are executed without reading or writing data
- NO SQL Indicates that the routine does not haveSQL语句
- READS SQL DATA Indicates that the routine contains a statement to read data(比如select)But there is no statement to write the data
- MODIFIES SQL DATA Indicates that the routine contains statements that may write data(比如insert或delete)
- SQL SECURITY characteristics can beDEFINERdefiner orINVOKERThe caller specifies the security context;就是,Execute the routine with the privileges of whose account,Is routineDEFINERDefine the named user in the statement?or the user executing the routine?The account must have a routine to use own database permissions,SQL SECURITY默认值是DEFINER,即由DEFINERThe privileges of the account of the named user defined in the statement to execute the routine,The user calling the routine must have the routine's executionEXECUTE权限,If the routine executes in the definer security context,the definer account must also have this permission(不理解,什么是“安全上下文”?自我理解,The security context is whose authority is used to execute the code content in the stored procedure.首先,The caller needs permission to call the stored procedure again,While the stored procedure is executing,for which libraries、Which tables perform what operations,and other unpaired libraries、表的操作,Permission to do these operations,是要看SQL SECURITY 后面指定DEFINER还是INVOKER,其中SQL SECURITY DEFINER是默认值,可以不用写,如果需要指定INVOKERneed to be written explicitly)
- DEFINERclause specifies that when the routine executes, checks haveSQL SECURITY DEFINERTo use when accessing the attribute's routinesMySQL帐户
- 如果有DEFINER子句,那userThe format of the field should be ‘user_name’@‘host_name’,CURRENT_USER或CURRENT_USER().允许的userThe value depends on the permissions I have,For more information on stored procedure security see:https://dev.mysql.com/doc/refman/8.0/en/stored-objects-security.html
- 如果DEFINERfeature is omitted,The definition of the default is to execute the stored procedure or method of the user,这与写“DEFINER = CURRENT_USER”效果一样
- 在定义了SQL SECURITY DEFINERin the code body of the routine,CURRENT_USERThe method returns the routineDEFINER值,For user auditing in stored routines,看:https://dev.mysql.com/doc/refman/8.0/en/account-activity-auditing.html
- 看下面“DEFINER ‘admin’@‘localhost’”代码块:no matter which user-defined,stored procedure will define’admin’@'localhost’用户为DEGINER;No matter which user executes the stored procedure,The execution of the stored procedure will useDEFINERPermissions for the specified user.The success or failure of stored procedure execution depends on whether the caller has execute permission、DEFINER指定的adminDoes the user havemysql.user表的查询权限
- 看下面“SQL SECURITY INVOKER”代码块,Now specify the security context as the stored procedure callerSQL SECURITY INVOKER:Still a stored procedure specifiedDEFINER = ‘admin’@‘localhost’,但是在这个例子中,The stored procedure is executed with the permissions of the caller,因此,The success or failure of the execution of the stored procedure depends on whether the caller has the calling authority of the stored procedure and themysql.user表的select权限
- Server processing of stored procedure parameters、stored procedure methodDECLARECreated local variables、The data type of the method return value, etc.:
- For the data type mismatches and overflow problem and matching tests,在严格的SQLMode conversion and overflow issues cause warnings、错误
- Only scalar values can be specified,比如,“set x = (select 1,2)”是非法的
- 对于字符数据类型,如果CHARACTER SETwhen included in a declaration,The specified character set and its default validation rules will be used,如果COLLATEparameters are also declared,then the verification will useCOLLATEspecified validation rules instead of the default
如果CHARACTER SET和COLLATE都没有声明,Use the database character set and collation in effect at the time the routine was created.In order to avoid letting the server use the database character set and validation rules,provides explicit character data parameter settingsCHARACTER SET和COLLATE
If you change the database default character set and validation rules,The default value of the stored procedure using the new database must be deleted and recreated
The database character set and validation rules arecharacter_set_database和collation_database两个系统变量,For more information see:https://dev.mysql.com/doc/refman/8.0/en/charset-database.html
DEFINER = ‘admin’@‘localhost’
CREATE DEFINER = 'admin'@'localhost' PROCEDURE account_count()
BEGIN
SELECT 'Number of accounts:', COUNT(*) FROM mysql.user;
END;
SQL SECURITY INVOKER
CREATE DEFINER = 'admin'@'localhost' PROCEDURE account_count()
SQL SECURITY INVOKER
BEGIN
SELECT 'Number of accounts:', COUNT(*) FROM mysql.user;
END;
边栏推荐
猜你喜欢
随机推荐
安装MySQL的详细步骤
基于语音识别的QT设计的csgo互动类视频游戏
LeetCode_Dec_3rd_Week
MySQL基础
LeetCode_Dec_1st_Week
JUC并发容器——跳表
Tensorflow/Pytorch安装(Anaconda环境下,无版本冲突,亲测有效)
LeetCode_Dec_2nd_Week
strlen 转义字符
指针的运算【C语言】
JVM intro
C语言对文件的操作(完整版)
[Daily office][shell] Common code snippets
C语言静态变量static的分析
虚幻引擎 5 完整指南[2022六月最新课程学习内容]
2020-03-27
Deep learning, "grain and grass" first--On the way to obtain data sets
Copy Siege Lion's Annual "Battle" | Review 2020
MySQL批量修改时间字段
基于Webrtc和Janus的多人视频会议系统开发6 - 从Janus服务器订阅媒体流