MySql Stored Procedure processing with Parameters

Source: Internet
Author: User

The MySql stored procedure described below is a stored procedure with parameters (dynamic execution of SQL statements). This MySql Stored Procedure queries user information based on user input conditions and sorting methods, there is no call Method for sorting conditions:

Call GetUsersDynamic (age <= 30 ,);

 

 
 
  1. /******** Dynamically query user information ********/
  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 () is a custom function that returns the short format of a date.

 

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

MySql Stored Procedure for dynamic data insertion (note that four single quotes indicate one single quotation mark ):

 

 
 
  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;  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.