当前位置:Gxlcms > mysql > MySql存储过程带参数处理方式_MySQL

MySql存储过程带参数处理方式_MySQL

时间:2021-07-01 10:21:17 帮助过:22人阅读

  下文介绍的MySql存储过程是带参数的存储过程(动态执行SQL语句),该MySql存储过程是根据用户输入的条件和排序方式查询用户的信息,排序条件可以没有调用方式:

  call GetUsersDynamic('age<=30','');

  1. /********动态查询用户的信息********/
  2. CREATE PROCEDURE GetUsersDynamic(WhereCondition varchar(500),OrderByExpress varchar(100))
  3. begin
  4. declare stmt varchar(2000);
  5. if LENGTH(OrderbyExpress)>0 then
  6. begin
  7. set @sqlstr=concat('select id,name,password,age,getdate(adddate) as AddDate from users where ',WhereCondition,' order by ',OrderByExpress);
  8. end;
  9. else
  10. begin
  11. set @sqlstr=concat('select id,name,password,age,getdate(adddate) as AddDate from users where ',WhereCondition);
  12. end;
  13. end if;
  14. prepare stmt from @sqlstr;
  15. execute stmt;
  16. end;

  getdate()是一个自定义的函数,作用是返回日期的短格式

  1. CREATE DEFINER=`root`@`localhost` FUNCTION `getdate`($date datetime) RETURNS varchar(50) CHARSET latin1
  2. return date_format($date,'%Y-%m-%d');

  动态插入数据的MySql存储过程,(注意四个单引号表示一个一引号):

  1. CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertUser`(in name2 varchar(50),in password2 varchar(32),in age2 int,in adddate2 datetime)
  2. begin
  3. DECLARE stmt varchar(2000);
  4. set @sqlstr=concat('insert into users(name,password,age,adddate) values(');
  5. set @sqlstr=concat(@sqlstr,'''',name2,'''',',','''',password2,'''',',',age2,',','''',adddate2,'''',')');
  6. prepare stmt from @sqlstr;
  7. execute stmt;
  8. end;

人气教程排行