• SQL语法基础之高级应用


                          SQL语法基础之高级应用

                                         作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

    一.存储过程与函数

    1>.CREATE PROCEDURE 用来创建存储过程

    mysql> ? CREATE PROCEDURE
    Name: 'CREATE PROCEDURE'
    Description:
    Syntax:
    CREATE
        [DEFINER = { user | CURRENT_USER }]
        PROCEDURE sp_name ([proc_parameter[,...]])
        [characteristic ...] routine_body
    
    CREATE
        [DEFINER = { user | CURRENT_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
    
    These statements create stored routines. By default, a routine is
    associated with the default database. To associate the routine
    explicitly with a given database, specify the name as db_name.sp_name
    when you create it.
    
    The CREATE FUNCTION statement is also used in MySQL to support UDFs
    (user-defined functions). See
    http://dev.mysql.com/doc/refman/8.0/en/adding-functions.html. A UDF can
    be regarded as an external stored function. Stored functions share
    their namespace with UDFs. See
    http://dev.mysql.com/doc/refman/8.0/en/function-resolution.html, for
    the rules describing how the server interprets references to different
    kinds of functions.
    
    To invoke a stored procedure, use the CALL statement (see [HELP CALL]).
    To invoke a stored function, refer to it in an expression. The function
    returns a value during expression evaluation.
    
    CREATE PROCEDURE and CREATE FUNCTION require the CREATE ROUTINE
    privilege. They might also require the SET_USER_ID or SUPER privilege,
    depending on the DEFINER value, as described later in this section. If
    binary logging is enabled, CREATE FUNCTION might require the SUPER
    privilege, as described in
    http://dev.mysql.com/doc/refman/8.0/en/stored-programs-logging.html.
    
    By default, MySQL automatically grants the ALTER ROUTINE and EXECUTE
    privileges to the routine creator. This behavior can be changed by
    disabling the automatic_sp_privileges system variable. See
    http://dev.mysql.com/doc/refman/8.0/en/stored-routines-privileges.html.
    
    The DEFINER and SQL SECURITY clauses specify the security context to be
    used when checking access privileges at routine execution time, as
    described later in this section.
    
    If the routine name is the same as the name of a built-in SQL function,
    a syntax error occurs unless you use a space between the name and the
    following parenthesis when defining the routine or invoking it later.
    For this reason, avoid using the names of existing SQL functions for
    your own stored routines.
    
    The IGNORE_SPACE SQL mode applies to built-in functions, not to stored
    routines. It is always permissible to have spaces after a stored
    routine name, regardless of whether IGNORE_SPACE is enabled.
    
    The parameter list enclosed within parentheses must always be present.
    If there are no parameters, an empty parameter list of () should be
    used. Parameter names are not case sensitive.
    
    Each parameter is an IN parameter by default. To specify otherwise for
    a parameter, use the keyword OUT or INOUT before the parameter name.
    
    *Note*:
    
    Specifying a parameter as IN, OUT, or INOUT is valid only for a
    PROCEDURE. For a FUNCTION, parameters are always regarded as IN
    parameters.
    
    An IN parameter passes a value into a procedure. The procedure might
    modify the value, but the modification is not visible to the caller
    when the procedure returns. An OUT parameter passes a value from the
    procedure back to the caller. Its initial value is NULL within the
    procedure, and its value is visible to the caller when the procedure
    returns. An INOUT parameter is initialized by the caller, can be
    modified by the procedure, and any change made by the procedure is
    visible to the caller when the procedure returns.
    
    For each OUT or INOUT parameter, pass a user-defined variable in the
    CALL statement that invokes the procedure so that you can obtain its
    value when the procedure returns. If you are calling the procedure from
    within another stored procedure or function, you can also pass a
    routine parameter or local routine variable as an OUT or INOUT
    parameter. If you are calling the procedure from within a trigger, you
    can also pass NEW.col_name as an OUT or INOUT parameter.
    
    Routine parameters cannot be referenced in statements prepared within
    the routine; see
    http://dev.mysql.com/doc/refman/8.0/en/stored-program-restrictions.html
    .
    
    The following example shows a simple stored procedure that uses an OUT
    parameter:
    
    mysql> delimiter //
    
    mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
        -> BEGIN
        ->   SELECT COUNT(*) INTO param1 FROM t;
        -> END//
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> delimiter ;
    
    mysql> CALL simpleproc(@a);
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT @a;
    +------+
    | @a   |
    +------+
    | 3    |
    +------+
    1 row in set (0.00 sec)
    
    The example uses the mysql client delimiter command to change the
    statement delimiter from ; to // while the procedure is being defined.
    This enables the ; delimiter used in the procedure body to be passed
    through to the server rather than being interpreted by mysql itself.
    See
    http://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html.
    
    The RETURNS clause may be specified only for a FUNCTION, for which it
    is mandatory. It indicates the return type of the function, and the
    function body must contain a RETURN value statement. If the RETURN
    statement returns a value of a different type, the value is coerced to
    the proper type. For example, if a function specifies an ENUM or SET
    value in the RETURNS clause, but the RETURN statement returns an
    integer, the value returned from the function is the string for the
    corresponding ENUM member of set of SET members.
    
    The following example function takes a parameter, performs an operation
    using an SQL function, and returns the result. In this case, it is
    unnecessary to use delimiter because the function definition contains
    no internal ; statement delimiters:
    
    mysql> CREATE FUNCTION hello (s CHAR(20))
    mysql> RETURNS CHAR(50) DETERMINISTIC
        -> RETURN CONCAT('Hello, ',s,'!');
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT hello('world');
    +----------------+
    | hello('world') |
    +----------------+
    | Hello, world!  |
    +----------------+
    1 row in set (0.00 sec)
    
    Parameter types and function return types can be declared to use any
    valid data type. The COLLATE attribute can be used if preceded by the
    CHARACTER SET attribute.
    
    The routine_body consists of a valid SQL routine statement. This can be
    a simple statement such as SELECT or INSERT, or a compound statement
    written using BEGIN and END. Compound statements can contain
    declarations, loops, and other control structure statements. The syntax
    for these statements is described in
    http://dev.mysql.com/doc/refman/8.0/en/sql-syntax-compound-statements.h
    tml.
    
    MySQL permits routines to contain DDL statements, such as CREATE and
    DROP. MySQL also permits stored procedures (but not stored functions)
    to contain SQL transaction statements such as COMMIT. Stored functions
    may not contain statements that perform explicit or implicit commit or
    rollback. Support for these statements is not required by the SQL
    standard, which states that each DBMS vendor may decide whether to
    permit them.
    
    Statements that return a result set can be used within a stored
    procedure but not within a stored function. This prohibition includes
    SELECT statements that do not have an INTO var_list clause and other
    statements such as SHOW, EXPLAIN, and CHECK TABLE. For statements that
    can be determined at function definition time to return a result set, a
    Not allowed to return a result set from a function error occurs
    (ER_SP_NO_RETSET). For statements that can be determined only at
    runtime to return a result set, a PROCEDURE %s can't return a result
    set in the given context error occurs (ER_SP_BADSELECT).
    
    USE statements within stored routines are not permitted. When a routine
    is invoked, an implicit USE db_name is performed (and undone when the
    routine terminates). The causes the routine to have the given default
    database while it executes. References to objects in databases other
    than the routine default database should be qualified with the
    appropriate database name.
    
    For additional information about statements that are not permitted in
    stored routines, see
    http://dev.mysql.com/doc/refman/8.0/en/stored-program-restrictions.html
    .
    
    For information about invoking stored procedures from within programs
    written in a language that has a MySQL interface, see [HELP CALL].
    
    MySQL stores the sql_mode system variable setting in effect when a
    routine is created or altered, and always executes the routine with
    this setting in force, regardless of the current server SQL mode when
    the routine begins executing.
    
    The switch from the SQL mode of the invoker to that of the routine
    occurs after evaluation of arguments and assignment of the resulting
    values to routine parameters. If you define a routine in strict SQL
    mode but invoke it in nonstrict mode, assignment of arguments to
    routine parameters does not take place in strict mode. If you require
    that expressions passed to a routine be assigned in strict SQL mode,
    you should invoke the routine with strict mode in effect.
    
    URL: http://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
    
    
    mysql> 
    查看创建存储过程的帮助信息( mysql> ? CREATE PROCEDURE)

    2>.CREATE FUNCTION用来创建函数 

    mysql> ? CREATE FUNCTION
    Name: 'CREATE FUNCTION'
    Description:
    The CREATE FUNCTION statement is used to create stored functions and
    user-defined functions (UDFs):
    
    o For information about creating stored functions, see [HELP CREATE
      PROCEDURE].
    
    o For information about creating user-defined functions, see [HELP
      CREATE FUNCTION UDF].
    
    URL: http://dev.mysql.com/doc/refman/8.0/en/create-function.html
    
    
    mysql> 
    mysql> 
    mysql> 
    查看创建函数的帮助信息(mysql> ? CREATE FUNCTION)

    3>.关键词说明 

    1>.函数与存储过程最大的区别就是函数调用有返回值,调用存储过程用call语句,而调用函数就直接引用函数名+参数即可! 
    
    2>.Definer和SQL SECURITY子句指定安全环境
        Definder是MySQL的特殊的访问控制手段,当数据库当前没有这个用户权限时,执行存储过程可能会报错。
        SQL SECURITY的值决定了调用存储过程的方式,其值为:definer(默认)或者invoker,详细说明如下:
            definer:在执行存储过程前验证definer对应的用户,如:yinzhengjie@127.0.0.1是否存在,以及是否具有执行存储过程的权限,若没有则报错。
            invoker:在执行存储过程时判断inovker即调用该存储过程的用户是否有相应权限,若没有则报错。
    
    3>.IN,OUT,INOUT三个参数前的关键词只适用于存储过程,对函数而言所有的参数默认都是输入参数。
    
    4>.IN输入参数用于把数值传入到存储过程中;OUT输出参数将数值传递到调用者,初始值是NULL;INOUT输入输出参数把数据传入到存储过程,在存储过程中修改之后再传递到调用者。
    
    5>.DELIMITER命令是改变语句的结束符,MySQL默认的结束符为分号(”;”),由于PROCEDURE和FUNCTION中 的分号(”;”)并不代表创建的结束,所以要替换成另外的结束符以便表示创建的结束。
    
    
6>.Rontine_body 子句可以包含一个简单的SQL语句,也可以包含多个 SQL语句,通过begin...end将这多个SQL语句包含在一起 

    
    7>.MySQL存储过程和函数中也可以包含类似create和drop等DDL语句 

    
    8>.Comment子句用来写入对存储过程和函数的注释 

    
    9>.Language子句用来表示此存储过程和函数的创建语言 
    
    10>.存储过程和函数被标注为deterministic表明当输入相同的参数是会 返回相同的结果,反之如果是not deterministic则表示相同参数不 会是相同结果,默认是not deterministic 

    
    11>.相关属性短语只有咨询含义,并不是强制性的约束
    Contains sql表明此存储过程或函数不包含读或者写数据的语句,这是默认属性 
        NO SQL表示此存储过程或函数不包含SQL语句 
        Reads sql data表示此存储过程包含诸如select的查询数据的语句,但不包含插入或删除数据的语句 
        Modifies sql data表示此存储过程包含插入或删除数据的语句 
     
    12>.Drop procedure/function语句用来删除指定名称的存储过程或函数 
    
    13>.IF EXISTS关键词用来避免在删除一个本身不存在的存储过程或函数时,MySQL返回错误

    
    14>.BEGIN...END语句通常出现在存储过程、函数和触发器中,其中可 以包含一个或多个语句,每个语句用分号(";")隔开

    4>.案例展示

      创建存储过程案例一:

    mysql> SELECT DATABASE();
    +-------------+
    | DATABASE()  |
    +-------------+
    | yinzhengjie |
    +-------------+
    row in set (0.00 sec)
    
    mysql> 
    mysql> SHOW TABLES;
    +-----------------------+
    | Tables_in_yinzhengjie |
    +-----------------------+
    | course                |
    | score_graph           |
    | student               |
    | teacher               |
    | view_teacher          |
    +-----------------------+
    rows in set (0.00 sec)
    
    mysql> 
    mysql> SELECT * FROM teacher;
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    |  1 | 谢霆锋    |        11 |
    |  2 | 周杰伦    |         1 |
    |  3 | 蔡依林    |        13 |
    |  4 | 杨幂      |         2 |
    |  5 | 胡歌      |        12 |
    |  6 | 刘德华    |         3 |
    |  7 | 张学友    |        10 |
    |  8 | 郭德纲    |         4 |
    |  9 | 林俊杰    |         9 |
    +----+-----------+-----------+
    rows in set (0.00 sec)
    
    mysql> 
    mysql> DELIMITER //
    mysql> 
    mysql> CREATE PROCEDURE demo(IN args1 int,OUT args2 INT)
        -> BEGIN
        ->  SELECT COUNT(*) INTO args2 FROM teacher where id> args1; 
        -> END//
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> 
    mysql> DELIMITER ;
    mysql> 
    mysql> 
    创建存储过程案例展示
    mysql> CALL demo2(2,@res); 
    Query OK, 1 row affected (0.00 sec)
    
    mysql> 
    mysql> SELECT @res;
    +------+
    | @res |
    +------+
    |    7 |
    +------+
    1 row in set (0.00 sec)
    
    mysql> 
    调用存储过程案例展示

      创建存储过程案例二: 

    [root@node110 ~]# mysql -uroot -pyinzhengjie
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or g.
    Your MySQL connection id is 18
    Server version: 8.0.14 MySQL Community Server - GPL
    
    Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
    
    mysql> 
    mysql> CREATE USER 'jason'@'node110.yinzhengjie.org.cn' IDENTIFIED BY 'yinzhengjie';
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> 
    mysql> SELECT Host,User FROM mysql.user WHERE Host = 'node110.yinzhengjie.org.cn';
    +----------------------------+-------+
    | Host                       | User  |
    +----------------------------+-------+
    | node110.yinzhengjie.org.cn | jason |
    +----------------------------+-------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SHOW GRANTS FOR 'jason'@'node110.yinzhengjie.org.cn';
    +------------------------------------------------------------+
    | Grants for jason@node110.yinzhengjie.org.cn                |
    +------------------------------------------------------------+
    | GRANT USAGE ON *.* TO `jason`@`node110.yinzhengjie.org.cn` |
    +------------------------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> GRANT ALL PRIVILEGES ON yinzhengjie.* TO `jason`@`node110.yinzhengjie.org.cn` WITH GRANT OPTION;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> 
    mysql> SHOW GRANTS FOR 'jason'@'node110.yinzhengjie.org.cn';
    +---------------------------------------------------------------------------------------------------+
    | Grants for jason@node110.yinzhengjie.org.cn                                                       |
    +---------------------------------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO `jason`@`node110.yinzhengjie.org.cn`                                        |
    | GRANT ALL PRIVILEGES ON `yinzhengjie`.* TO `jason`@`node110.yinzhengjie.org.cn` WITH GRANT OPTION |
    +---------------------------------------------------------------------------------------------------+
    2 rows in set (0.00 sec)
    
    mysql> 
    [root@node110 ~]# hostname
    node110.yinzhengjie.org.cn
    [root@node110 ~]# 
    [root@node110 ~]# mysql -h node110.yinzhengjie.org.cn  -ujason -pyinzhengjie  
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or g.
    Your MySQL connection id is 23
    Server version: 8.0.14 MySQL Community Server - GPL
    
    Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
    
    mysql> SHOW DATABASES;
    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | yinzhengjie        |
    +--------------------+
    2 rows in set (0.00 sec)
    
    mysql> 
    mysql> USE yinzhengjie
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A
    
    Database changed
    mysql> 
    mysql> SHOW TABLES
        -> ;
    +-----------------------+
    | Tables_in_yinzhengjie |
    +-----------------------+
    | course                |
    | score_graph           |
    | student               |
    | teacher               |
    | view_teacher          |
    +-----------------------+
    5 rows in set (0.00 sec)
    
    mysql> 
    mysql> SELECT * FROM teacher;
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    |  1 | 谢霆锋    |        11 |
    |  2 | 周杰伦    |         1 |
    |  3 | 蔡依林    |        13 |
    |  4 | 杨幂      |         2 |
    |  5 | 胡歌      |        12 |
    |  6 | 刘德华    |         3 |
    |  7 | 张学友    |        10 |
    |  8 | 郭德纲    |         4 |
    |  9 | 林俊杰    |         9 |
    | 16 | Jason Yin |         8 |
    +----+-----------+-----------+
    10 rows in set (0.00 sec)
    
    mysql> 
    创建存储过程案例展示二之环境准备(创建测试用户并授权)
    mysql> SELECT VERSION();
    +-----------+
    | VERSION() |
    +-----------+
    | 8.0.14    |
    +-----------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> SELECT USER();
    +----------------------------------+
    | USER()                           |
    +----------------------------------+
    | jason@node110.yinzhengjie.org.cn |
    +----------------------------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT DATABASE();
    +-------------+
    | DATABASE()  |
    +-------------+
    | yinzhengjie |
    +-------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> DELIMITER //
    mysql> 
    mysql> CREATE PROCEDURE myproc(IN args1 INT,OUT args2 INT)
        -> 
        -> BEGIN
        -> 
        -> SELECT COUNT(*) INTO args2 FROM teacher WHERE course_id > args1;
        -> 
        -> END//
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql> DELIMITER ;
    mysql> 
    创建存储过程案例展示二
    mysql> SELECT VERSION();
    +-----------+
    | VERSION() |
    +-----------+
    | 8.0.14    |
    +-----------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> SELECT DATABASE();
    +-------------+
    | DATABASE()  |
    +-------------+
    | yinzhengjie |
    +-------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT USER();
    +----------------------------------+
    | USER()                           |
    +----------------------------------+
    | jason@node110.yinzhengjie.org.cn |
    +----------------------------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> CALL myproc(5,@res);
    Query OK, 1 row affected (0.00 sec)
    
    mysql> 
    mysql> SELECT @res;
    +------+
    | @res |
    +------+
    |    6 |
    +------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT COUNT(*)  FROM teacher WHERE course_id > 5;          
    +----------+
    | COUNT(*) |
    +----------+
    |        6 |
    +----------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> SELECT *  FROM teacher WHERE course_id > 5;        
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    | 16 | Jason Yin |         8 |
    |  9 | 林俊杰    |         9 |
    |  7 | 张学友    |        10 |
    |  1 | 谢霆锋    |        11 |
    |  5 | 胡歌      |        12 |
    |  3 | 蔡依林    |        13 |
    +----+-----------+-----------+
    6 rows in set (0.00 sec)
    
    mysql> 
    mysql> 
    调用存储过程案例展示二
    mysql> SELECT VERSION();
    +-----------+
    | VERSION() |
    +-----------+
    | 8.0.14    |
    +-----------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT DATABASE();
    +-------------+
    | DATABASE()  |
    +-------------+
    | yinzhengjie |
    +-------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT USER();
    +----------------+
    | USER()         |
    +----------------+
    | root@localhost |
    +----------------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> CALL myproc(5,@res);
    Query OK, 1 row affected (0.01 sec)
    
    mysql> 
    mysql> SELECT @res;
    +------+
    | @res |
    +------+
    |    6 |
    +------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> 
    mysql> DROP USER jason@node110.yinzhengjie.org.cn;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql> CALL myproc(5,@res);
    ERROR 1449 (HY000): The user specified as a definer ('jason'@'node110.yinzhengjie.org.cn') does not exist
    mysql> 
    mysql> ALTER PROCEDURE myproc SQL SECURITY INVOKER;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> 
    mysql> CALL myproc(5,@res);
    Query OK, 1 row affected (0.00 sec)
    
    mysql> 
    mysql> SELECT @res;
    +------+
    | @res |
    +------+
    |    6 |
    +------+
    1 row in set (0.00 sec)
    
    mysql> 
    调用存储过程案例展示二(删除创建存储过程的用户时无法调用的解决方案,使用SQL SECURITY INVOKER)

      创建函数案例一:

    mysql> set global log_bin_trust_function_creators=TRUE;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql> CREATE FUNCTION hello(str CHAR(30))
        -> RETURNS CHAR(50)
        ->  RETURN CONCAT('Hello,',str,'!');
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    创建函数案例展示
    mysql> set global log_bin_trust_function_creators=TRUE;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql> CREATE FUNCTION hello(str CHAR(30))
        -> RETURNS CHAR(50)
        ->  RETURN CONCAT('Hello,',str,'!');
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql> SELECT hello('尹正杰');
    +--------------------+
    | hello('尹正杰')    |
    +--------------------+
    | Hello,尹正杰!      |
    +--------------------+
    1 row in set, 2 warnings (0.00 sec)
    
    mysql> 
    mysql> 
    调用函数案例展示

      创建函数案例二:

    mysql> SELECT * FROM yinzhengjie.teacher;
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    |  1 | 谢霆锋    |        11 |
    |  2 | 周杰伦    |         1 |
    |  3 | 蔡依林    |        13 |
    |  4 | 杨幂      |         2 |
    |  5 | 胡歌      |        12 |
    |  6 | 刘德华    |         3 |
    |  7 | 张学友    |        10 |
    |  8 | 郭德纲    |         4 |
    |  9 | 林俊杰    |         9 |
    | 16 | 尹正杰    |         8 |
    +----+-----------+-----------+
    10 rows in set (0.00 sec)
    
    mysql> 
    mysql> DELIMITER //
    mysql> CREATE FUNCTION myfunc(args1 INT)    
        -> RETURNS INT
        -> BEGIN
        -> UPDATE yinzhengjie.teacher SET name = 'Jason Yin' WHERE id = args1;
        -> SELECT COUNT(*) INTO @res FROM yinzhengjie.teacher WHERE course_id % args1 = 0; 
        -> RETURN @res;
        -> END//
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql> DELIMITER ;
    创建函数案例展示二
    mysql> DELIMITER //
    mysql> CREATE FUNCTION myfunc(args1 INT)    
        -> RETURNS INT
        -> BEGIN
        -> UPDATE yinzhengjie.teacher SET name = 'Jason Yin' WHERE id = args1;
        -> SELECT COUNT(*) INTO @res FROM yinzhengjie.teacher WHERE course_id % args1 = 0; 
        -> RETURN @res;
        -> END//
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> 
    mysql>  DELIMITER ;
    mysql> 
    mysql> 
    mysql> SELECT * FROM yinzhengjie.teacher;
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    |  1 | 谢霆锋    |        11 |
    |  2 | 周杰伦    |         1 |
    |  3 | 蔡依林    |        13 |
    |  4 | 杨幂      |         2 |
    |  5 | 胡歌      |        12 |
    |  6 | 刘德华    |         3 |
    |  7 | 张学友    |        10 |
    |  8 | 郭德纲    |         4 |
    |  9 | 林俊杰    |         9 |
    | 16 | 尹正杰    |         8 |
    +----+-----------+-----------+
    rows in set (0.00 sec)
    
    mysql> 
    mysql> SELECT myfunc(16);
    +------------+
    | myfunc(16) |
    +------------+
    |          0 |
    +------------+
    row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT * FROM yinzhengjie.teacher;
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    |  1 | 谢霆锋    |        11 |
    |  2 | 周杰伦    |         1 |
    |  3 | 蔡依林    |        13 |
    |  4 | 杨幂      |         2 |
    |  5 | 胡歌      |        12 |
    |  6 | 刘德华    |         3 |
    |  7 | 张学友    |        10 |
    |  8 | 郭德纲    |         4 |
    |  9 | 林俊杰    |         9 |
    | 16 | Jason Yin |         8 |
    +----+-----------+-----------+
    rows in set (0.01 sec)
    
    mysql> 
    mysql> SELECT COUNT(*) FROM yinzhengjie.teacher WHERE course_id % 16 = 0;          
    +----------+
    | COUNT(*) |
    +----------+
    |        0 |
    +----------+
    1 row in set (0.00 sec)
    
    mysql> 
    mysql> SELECT * FROM yinzhengjie.teacher WHERE course_id % 8 = 0;       
    +----+-----------+-----------+
    | id | name      | course_id |
    +----+-----------+-----------+
    | 16 | Jason Yin |         8 |
    +----+-----------+-----------+
    1 row in set (0.00 sec)
    
    mysql> 
    调用函数案例展示二

      删除创建过程案例:

    mysql> DROP PROCEDURE demo;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> 
    mysql> DROP PROCEDURE demo;
    ERROR 1305 (42000): PROCEDURE yinzhengjie.demo does not exist
    mysql> 
    mysql> 
    mysql> 
    mysql> DROP PROCEDURE IF EXISTS demo;   
    Query OK, 0 rows affected, 1 warning (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> DROP PROCEDURE IF EXISTS demo;

      删除函数案例:

    mysql> DROP FUNCTION hello;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> 
    mysql> DROP FUNCTION hello;
    ERROR 1305 (42000): FUNCTION yinzhengjie.hello does not exist
    mysql> 
    mysql> 
    mysql> DROP FUNCTION IF EXISTS hello;
    Query OK, 0 rows affected, 1 warning (0.00 sec)
    
    mysql> 
    mysql> 
    mysql> DROP FUNCTION IF EXISTS hello;

    5>.查看已经存在的存储过程或者函数

    mysql> SELECT routine_name,routine_type FROM information_schema.routines WHERE routine_schema='course';
    +--------------+--------------+
    | ROUTINE_NAME | ROUTINE_TYPE |
    +--------------+--------------+
    | hello        | FUNCTION     |
    | myfunc       | FUNCTION     |
    | demo         | PROCEDURE    |      
    | myproc       | PROCEDURE    |
    +--------------+--------------+
    4 rows in set (0.01 sec)
    
    mysql> 
    mysql>  

    二.标签语句

    1>.标签语句注意事项

    • 标签label可以加在begin...end语句以及loop, repeat和while语句
    
    • 语句中通过iterate和leave来控制流程,iterate表示返回指定标签 位置,leave表示跳出标签

    2>.案例展示

    三.

    四.

    五.

  • 相关阅读:
    git使用
    silverlight与wcf双向通讯 例子
    Oracle 存储过程
    C# 视频教程
    佩服的技术大牛 “赵劼”
    setTimeout setInterval
    js闭包
    MVC Razor视图引擎控件
    MVC json
    springboot创建多环境profile打包
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/10360310.html
Copyright © 2020-2023  润新知