简体   繁体   中英

mysql stored procedure select and update selected

i am trying to write a stored procedure for mysql, and basicly, it will select one id, and update selected id's operationdate.

DELIMITER //
 CREATE PROCEDURE getID(
  IN proc_intervaldate datetime
 )

 BEGIN
    DECLARE RUserID BIGINT;
    SELECT 
        UserID 
    INTO RUserID 
    FROM Tasks
    WHERE  OperationDate < proc_intervaldate
    LIMIT 1 ;

    UPDATE Tasks SET OperationDate = now() WHERE UserID = RUserID;

    SELECT RUserID ;


 END //
DELIMITER ;

but when i use this, procedure, it will return UserID but not update, if i comment

SELECT RUserID

then, it updates, but no data returns.

when I use this, procedure, it will return UserID but not update, if I comment 'SELECT RUserID;' then, it updates, but no data returns.

You can change definition of stored procedure to use an OUT parameter rather than just IN . With that, you can just capture the OUT value on the same OUT parameter, in your scripting language. Meaning you need not execute:

SELECT RUserID ;

in your stored procedure.

Change your SP definition as below:

DELIMITER //
CREATE PROCEDURE getID( IN proc_intervaldate datetime, OUT RUserID bigint )
BEGIN
    SELECT 
      UserID INTO RUserID 
    FROM Tasks
    WHERE 
      OperationDate < proc_intervaldate
    LIMIT 1 ;

    UPDATE Tasks SET OperationDate = now() WHERE UserID = RUserID;
END;
//
DELIMITER ;

You can call this stored procedure like, for example, at MySQL console:

SET @RUserID := 0;
CALL getID( now(), @RUserID );
SELECT @RUserID;

Refer to :

  • MySQL: CALL procedure syntax
    • To get back a value from a procedure using an OUT or INOUT parameter, pass the parameter by means of a user variable, and then check the value of the variable after the procedure returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM