日期:2014-05-16  浏览次数:20817 次

mysql prepare 存储过程使用

语法

[sql]
  1. PREPARE?statement_name?FROM?sql_text?/*定义*/???
  2. EXECUTE?statement_name?[USING?variable?[,variable...]]?/*执行预处理语句*/???
  3. DEALLOCATE?PREPARE?statement_name?/*删除定义*/???


[sql]
  1. mysql>?PREPARE?prod?FROM?"INSERT?INTO?examlple?VALUES(?,?)";???
  2. mysql>?SET?@p='1';???
  3. mysql>?SET?@q='2';???
  4. mysql>?EXECUTE?prod?USING?@p,@q;???
  5. mysql>?SET?@name='3';???
  6. mysql>?EXECUTE?prod?USING?@p,@name;???
  7. mysql>?DEALLOCATE?PREPARE?prod;??


1.用变量做表名: 简单的用set或者declare语句定义变量,然后直接作为sql的表名是不行的,mysql会把变量名当作表名。在其他的sql数据库中也是如 此,mssql的解决方法是将整条sql语句作为变量,其中穿插变量作为表名,然后用sp_executesql调用该语句。 这在mysql5.0之前是不行的,5.0之后引入了一个全新的语句,可以达到类似sp_executesql的功能(仅对procedure有 效,function不支持动态查询):?

PREPARE stmt_name FROM preparable_stmt;
EXECUTE stmt_name [USING @var_name [, @var_name] ...];
{DEALLOCATE | DROP} PREPARE stmt_name;?

?

为了有一个感性的认识,下面先给几个小例子:?

?

[sql]
  1. mysql>?PREPARE?stmt1?FROM?'SELECT?SQRT(POW(?,2)?+?POW(?,2))?AS?hypotenuse';???
  2. mysql>?SET?@a?=?3;???
  3. mysql>?SET?@b?=?4;???
  4. mysql>?EXECUTE?stmt1?USING?@a,?@b;???
  5. +------------+???
  6. |?hypotenuse?|???
  7. +------------+???
  8. |?5?|???
  9. +------------+???
  10. mysql>?DEALLOCATE?PREPARE?stmt1;???
  11. mysql>?SET?@s?=?'SELECT?SQRT(POW(?,2)?+?POW(?,2))?AS?hypotenuse';???
  12. mysql>?PREPARE?stmt2?FROM?@s;???
  13. mysql>?SET?@a?=?6;??