小题大做之MySQL 5.0存储过程编程入门

原作者:小强    原文链接:http://www.cnblogs.com/hsqzzzl/archive/2008/02/21/1076646.html

MySQL 版本:5.0.45    phpMyAdmin版本:2.11.3

 

首先看MySQL 5.0参考手册中关于创建存储过程的语法说明:

 

CREATE
    [DEFINER = { user | CURRENT_USER }]
    PROCEDURE sp_name ([proc_parameter[,...]])
    [characteristic ...] routine_body
    
proc_parameter
:
    [ IN | OUT | INOUT ] param_name type

type
:
    Any valid MySQL data type

characteristic
:
    LANGUAGE SQL
  | [NOT] DETERMINISTIC
  | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
  | SQL SECURITY { DEFINER | INVOKER }
  | COMMENT 'string'

routine_body:
    Valid SQL procedure statement
 

如果你对MySQL还不太熟悉的话,单单看这个语法结构当然不足以进行MySQL存储过程编程。我之前基本都是使用MS SQL SERVER,所以以下记录我熟悉MySQL存储过程的过程,也是重点介绍MS SQL SERVER与MySQL区别较大的地方。

 

第一步,当然是写个Hello Word的存储过程,如下:

CREATE PROCEDURE phelloword()

BEGIN

  SELECT 'Hello Word!' AS F;

END;

 

将上面创建phelloword存储过程的语句拷到phpMyAdmin中执行,报如下错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3

 

在这个问题上我纠缠了很久,在MySQL的命令行工具中执行同样不成功,但是根据提示信息可以知道执行在 SELECT 'Hello Word!' AS F;处结束,后面的END;没有执行,这显然会导致错误。

这里需要选择以个分隔符,语法如下:DELIMITER //

分隔符是通知MySQL客户端已经输入完成的符号。一直都是用“;”,但是在存储过程中不行,因为存储过程中很多语句都需要用到分号。

因此上面的存储过程改为:

CREATE PROCEDURE ptest()

BEGIN

  SELECT 'Hello Word!' AS F;

END //

 

另外在phpMyAdmin中执行时,在Delimiter文本框中填写 //,这次存储过程即可创建成功。

 

第二步,写一个包括参数,变量,变量赋值,条件判断,UPDATE语句,SELECT返回结果集的完整的一个存储过程,如下:

CREATE PROCEDURE plogin

(

    p_username char(15),

    p_password char(32),

    p_ip char(18),

    p_logintime datetime

)

LABEL_PROC:

BEGIN    

 

    DECLARE v_uid mediumint(8);  

    DECLARE v_realpassword char(32);     

    DECLARE v_nickname varchar(30);    

    DECLARE v_oltime smallint(6);      

   

    SELECT u.uid, u.password, f.nickname, u.oltime INTO v_uid, v_realpassword, v_nickname, v_oltime

    FROM cdb_members u INNER JOIN cdb_memberfields f ON f.uid = u.uid WHERE u.username = p_username;   

   

    IF (v_uid IS NULLTHEN

        SELECT AS ErrorCode;

        LEAVE LABEL_PROC;

    END IF;

 

    IF (p_password <> v_realpassword) THEN

        SELECT AS ErrorCode;

        LEAVE LABEL_PROC;

    END IF;

 

    UPDATE ipsp_userexpands SET lastloginip = p_ip, lastlogintime = p_logintime WHERE uid = v_uid;

 

    SELECT AS ErrorCode, v_uid AS uid, v_nickname AS nickname, v_oltime AS oltime;

 

END LABEL_PROC //

 

首先要说的是给变量赋值的语法,MySQL中使用SELECT u.uid, u.password, f.nickname, u.oltime INTO v_uid, v_realpassword, v_nickname, v_oltime FROM cdb_members u INNER JOIN cdb_memberfields f ON f.uid = u.uid WHERE u.username = p_username;这种方式给变量赋值。

 

其次是条件判断的语法结构,如下所示:

IF ... THEN

    ...;

ELSE

    IF ... THEN

      ...;

    ELSEIF

      ...;

    ELSE

      ...;

    END IF;

END IF;

 

最后说说LEAVE 语法的使用。当满足某种条件,不继续执行下面的SQL时,在MS SQL SERVER中使用RETURN语法,在MySQL中我没有找到对应的关键字,但是这里可以利用LEAVE语法来满足要求,在存储过程的BEGIN前定义一个标签,如:“LABEL_PROC:” 然后再需要用到RETURN中断执行的地方执行“LEAVE LABEL_PROC;”即可。

 

第三步,创建一个执行动态SQL的存储过程。

CREATE PROCEDURE ipsp_getresourcedir

(

    p_hashcode char(40)

)

LABEL_PROC:

BEGIN

 

    DECLARE v_sql varchar(200);

 

    SET v_sql = CONCAT('SELECT filedir FROM ipsp_resources WHERE hashcode =\'', p_hashcode, '\' LIMIT 0, 1');

 

    SET @sql = v_sql;

   

    PREPARE sl FROM @sql;

 

    EXECUTE sl;

   

    DEALLOCATE PREPARE sl;

 

END LABEL_PROC //

 

这里提一下 “\”是转义字符,拼接成的SQL类似 SELECT filedir FROM ipsp_resources WHERE hashcode ='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' LIMIT 0, 1

另外@sql这个属于用户变量,具体用法请查询MySQL参考手册。

 

如果有在MS SQL SERVER上编写存储过程的经验的话,看完这些,我想基本的MySQL存储过程编程应该可以应付了吧!

 

想了解更多的内容可查询MySQL参考手册或者相关书籍!

 

Keywords:MySQL,Stored Procedure,存储过程,小强,hsqzzzl,http://hi.baidu.com/hsqzzzl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MySQL Stored Procedure Programming Advance Praise for MySQL Stored Procedure Programming Preface Objectives of This Book Structure of This Book What This Book Does Not Cover Conventions Used in This Book Which Version? Resources Available at the Book's Web Site Using Code Examples Safari® Enabled How to Contact Us Acknowledgments Part I: Stored Programming Fundamentals Chapter 1. Introduction to MySQL Stored Programs Section 1.1. What Is a Stored Program? Section 1.2. A Quick Tour Section 1.3. Resources for Developers Using Stored Programs Section 1.4. Some Words of Advice for Developers Section 1.5. Conclusion Chapter 2. MySQL Stored Programming Tutorial Section 2.1. What You Will Need Section 2.2. Our First Stored Procedure Section 2.3. Variables Section 2.4. Parameters Section 2.5. Conditional Execution Section 2.6. Loops Section 2.7. Dealing with Errors Section 2.8. Interacting with the Database Section 2.9. Calling Stored Programs from Stored Programs Section 2.10. Putting It All Together Section 2.11. Stored Functions Section 2.12. Triggers Section 2.13. Calling a Stored Procedure from PHP Section 2.14. Conclusion Chapter 3. Language Fundamentals Section 3.1. Variables, Literals, Parameters, and Comments Section 3.2. Operators Section 3.3. Expressions Section 3.4. Built-in Functions Section 3.5. Data Types Section 3.6. MySQL 5 "Strict" Mode Section 3.7. Conclusion Chapter 4. Blocks, Conditional Statements, and Iterative Programming Section 4.1. Block Structure of Stored Programs Section 4.2. Conditional Control Section 4.3. Iterative Processing with Loops Section 4.4. Conclusion Chapter 5. Using SQL in Stored Programming Section 5.1. Using Non-SELECT SQL in Stored Programs Section 5.2. Using SELECT Statements with an INTO Clause Section 5.3. Creating and Using Cursors Section 5.4. Using Unbounded SELECT Statements Section 5.5. Performing Dynamic SQL with Prepared Statements Section 5.6. Handling SQL Errors: A Preview Section 5.7. Conclusion Chapter 6. Error Handling Section 6.1. Introduction to Error Handling Section 6.2. Condition Handlers Section 6.3. Named Conditions Section 6.4. Missing SQL:2003 Features Section 6.5. Putting It All Together Section 6.6. Handling Stored Program Errors in the Calling Application Section 6.7. Conclusion Part II: Stored Program Construction Chapter 7. Creating and Maintaining Stored Programs Section 7.1. Creating Stored Programs Section 7.2. Editing an Existing Stored Program Section 7.3. SQL Statements for Managing Stored Programs Section 7.4. Getting Information About Stored Programs Section 7.5. Conclusion Chapter 8. Transaction Management Section 8.1. Transactional Support in MySQL Section 8.2. Defining a Transaction Section 8.3. Working with Savepoints Section 8.4. Transactions and Locks Section 8.5. Transaction Design Guidelines Section 8.6. Conclusion Chapter 9. MySQL Built-in Functions Section 9.1. String Functions Section 9.2. Numeric Functions Section 9.3. Date and Time Functions Section 9.4. Other Functions Section 9.5. Conclusion Chapter 10. Stored Functions Section 10.1. Creating Stored Functions Section 10.2. SQL Statements in Stored Functions Section 10.3. Calling Stored Functions Section 10.4. Using Stored Functions in SQL Section 10.5. Conclusion Chapter 11. Triggers Section 11.1. Creating Triggers Section 11.2. Using Triggers Section 11.3. Trigger Overhead Section 11.4. Conclusion Part III: Using MySQL Stored Programs in Applications Chapter 12. Using MySQL Stored Programs in Applications Section 12.1. The Pros and Cons of Stored Programs in Modern Applications Section 12.2. Advantages of Stored Programs Section 12.3. Disadvantages of Stored Programs Section 12.4. Calling Stored Programs from Application Code Section 12.5. Conclusion Chapter 13. Using MySQL Stored Programs with PHP Section 13.1. Options for Using MySQL with PHP Section 13.2. Using PHP with the mysqli Extension Section 13.3. Using MySQL with PHP Data Objects Section 13.4. Conclusion Chapter 14. Using MySQL Stored Programs with Java Section 14.1. Review of JDBC Basics Section 14.2. Using Stored Programs in JDBC Section 14.3. Stored Programs and J2EE Applications Section 14.4. Using Stored Procedures with Hibernate Section 14.5. Using Stored Procedures with Spring Section 14.6. Conclusion Chapter 15. Using MySQL Stored Programs with Perl Section 15.1. Review of Perl DBD::mysql Basics Section 15.2. Executing Stored Programs with DBD::mysql Section 15.3. Conclusion Chapter 16. Using MySQL Stored Programs with Python Section 16.1. Installing the MySQLdb Extension Section 16.2. MySQLdb Basics Section 16.3. Using Stored Programs with MySQLdb Section 16.4. A Complete Example Section 16.5. Conclusion Chapter 17. Using MySQL Stored Programs with .NET Section 17.1. Review of ADO.NET Basics Section 17.2. Using Stored Programs in ADO.NET Section 17.3. Using Stored Programs in ASP.NET Section 17.4. Conclusion Part IV: Optimizing Stored Programs Chapter 18. Stored Program Security Section 18.1. Permissions Required for Stored Programs Section 18.2. Execution Mode Options for Stored Programs Section 18.3. Stored Programs and Code Injection Section 18.4. Conclusion Chapter 19. Tuning Stored Programs and Their SQL Section 19.1. Why SQL Tuning Is So Important Section 19.2. How MySQL Processes SQL Section 19.3. SQL Tuning Statements and Practices Section 19.4. About the Upcoming Examples Section 19.5. Conclusion Chapter 20. Basic SQL Tuning Section 20.1. Tuning Table Access Section 20.2. Tuning Joins Section 20.3. Conclusion Chapter 21. Advanced SQL Tuning Section 21.1. Tuning Subqueries Section 21.2. Tuning "Anti-Joins" Using Subqueries Section 21.3. Tuning Subqueries in the FROM Clause Section 21.4. Tuning ORDER and GROUP BY Section 21.5. Tuning DML (INSERT, UPDATE, DELETE) Section 21.6. Conclusion Chapter 22. Optimizing Stored Program Code Section 22.1. Performance Characteristics of Stored Programs Section 22.2. How Fast Is the Stored Program Language? Section 22.3. Reducing Network Traffic with Stored Programs Section 22.4. Stored Programs as an Alternative to Expensive SQL Section 22.5. Optimizing Loops Section 22.6. IF and CASE Statements Section 22.7. Recursion Section 22.8. Cursors Section 22.9. Trigger Overhead Section 22.10. Conclusion Chapter 23. Best Practices in MySQL Stored Program Development Section 23.1. The Development Process Section 23.2. Coding Style and Conventions Section 23.3. Variables Section 23.4. Conditional Logic Section 23.5. Loop Processing Section 23.6. Exception Handling Section 23.7. SQL in Stored Programs Section 23.8. Dynamic SQL Section 23.9. Program Construction Section 23.10. Performance Section 23.11. Conclusion About the Author Colophon Index
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值