Home > Database > Mysql Tutorial > MySql存储过程 带参数处理方式_MySQL

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 14:01:54
Original
1089 people have browsed it

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

  call GetUsersDynamic('age

 

<ol class="dp-sql">
<li class="alt">/********动态查询用户的信息********/    </li>
<li>CREATE PROCEDURE GetUsersDynamic(WhereCondition varchar(500),OrderByExpress varchar(100))    </li>
<li class="alt">begin    </li>
<li>declare stmt varchar(2000);    </li>
<li class="alt">if LENGTH(OrderbyExpress)>0 then    </li>
<li>begin    </li>
<li class="alt">     set @sqlstr=concat('select id,name,password,age,getdate(adddate) as AddDate from users where ',WhereCondition,' order by ',OrderByExpress);    </li>
<li>end;    </li>
<li class="alt">else    </li>
<li>begin    </li>
<li class="alt">     set @sqlstr=concat('select id,name,password,age,getdate(adddate) as AddDate from users where ',WhereCondition);    </li>
<li>end;    </li>
<li class="alt">end if;    </li>
<li>prepare stmt from @sqlstr;    </li>
<li class="alt">execute stmt;    </li>
<li>end;   </li>
</ol>
Copy after login

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

 

<ol class="dp-sql">
<li class="alt">CREATE DEFINER=`root`@`localhost` FUNCTION `getdate`($date datetime) RETURNS varchar(50) CHARSET latin1    </li>
<li>return date_format($date,'%Y-%m-%d');  </li>
</ol>
Copy after login

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

 

<ol class="dp-sql">
<li class="alt">CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertUser`(in name2 varchar(50),in password2 varchar(32),in age2 int,in adddate2 datetime)    </li>
<li>begin    </li>
<li class="alt">DECLARE stmt varchar(2000);    </li>
<li>set @sqlstr=concat('insert into users(name,password,age,adddate) values(');    </li>
<li class="alt">set @sqlstr=concat(@sqlstr,'''',name2,'''',',','''',password2,'''',',',age2,',','''',adddate2,'''',')');    </li>
<li>prepare stmt from @sqlstr;    </li>
<li class="alt">execute stmt;    </li>
<li>end;  </li>
</ol>
Copy after login

 

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template