MySQL stored procedure with parameter processing method

Source: Internet
Author: User
Tags date datetime end getdate sql mysql prepare stmt

The mysql stored procedure described below is a stored procedure with parameters (Dynamic execution of SQL statements) that queries the user's information based on the conditions and sort of user input, and the sorting criteria can be not invoked:

Call Getusersdynamic (' age<=30 ', ');

 
 
  1. /******** dynamically query the user's information ********/
  2. CREATE PROCEDURE getusersdynamic (wherecondition varchar), 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 the 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 a short form of the date

 
  
  
  1. CREATE definer= ' root ' @ ' localhost ' FUNCTION ' getdate ' ($date datetime) RETURNS varchar (m) CHARSET
  2. Return Date_format ($date, '%y-%m-%d ');

The mysql stored procedure for dynamically inserting data (note that four single quotes denote one quotation mark):

 
  
  
  1. CREATE definer= ' root ' @ ' localhost ' PROCEDURE ' insertuser ' (in name2 varchar (x), in Password2 varchar (x), in Age2 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, ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ',
  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.