简体   繁体   中英

How can I pass parameter to stored procedure through a query?

I have this stored procedure:

CREATE PROCEDURE `test`(OUT `vote_value` INT, OUT `score` INT, IN `user_id` INT, IN `time_range` INT)
    NO SQL
BEGIN
    SELECT coalesce(sum(vote_value), 0), coalesce(sum(score), 0)
      INTO vote_value, score
    FROM reputations
    WHERE owner_id = user_id
      AND date_time > CASE time_range
          WHEN 'WEEK' 
          THEN  unix_timestamp(DATE_SUB(now(), INTERVAL 1 WEEK))
          WHEN 'MONTH' 
          THEN  unix_timestamp(DATE_SUB(now(), INTERVAL 1 MONTH))
          WHEN 'YEAR' 
          THEN  unix_timestamp(DATE_SUB(now(), INTERVAL 1 YEAR))
          ELSE 1 END;
END

As you see my procedure gets 4 parameters. Both vote_value and score have OUT direction (as result) , And both user_id and time_range have IN Direction. So I have to pass those two which have IN direction when I call the procedure.

Ok, I can call procedure about like this:

CALL test(@vote_value, @score, 10, 'WEEK');
SELECT @vote_value, @score;

It would work as well. But please focus on the third parameter which is 10 . I don't want to pass it manually by hand. I want it be a value from a query. Something like this:

CALL test(@vote_value, @score, u.id, 'WEEK');
SELECT id, @vote_value, @score FROM Users u;

But it throws syntax error . Does anybody know how can I do such a thing? The expected result is this .

SELECT id into @id FROM Users LIMIT 1;
CALL test(@vote_value, @score, @id, 'WEEK');

Try above code.

As mention in above code you can get value of that id using SELECT id into @id and then use that @id as parameter for that query.

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