Home > Net >  How to set a value to a declared variable from a function call in MySQL?
How to set a value to a declared variable from a function call in MySQL?

Time:12-31

Let's say, I want to generate token and return it to user. I declare a variable new_token and I tried to pass it a value from procedure generate_token(). It might not work with procedures, because they are not allowed to be used in expressions. But it does not work with functions either way.

Code:

DECLARE new_token varchar(255);
SET new_token = CALL generate_token(lg);

I tried to assign to a local variable from a function call and from procedure, but neither of them did work. Can you help me out?

CodePudding user response:

In MySQL, you can set the value of a variable by using the SET statement. Here's an example of how you can set the value of a variable var1 to the result of a function call:

SET @var1 = function_name(arg1, arg2, ...);

For example, if you have a function called get_customer_count that returns the number of customers in a table, you can set the value of @var1 to the result of this function as follows:

SET @var1 = get_customer_count();

You can then use the @var1 variable in a subsequent query, like this:

SELECT * FROM customers WHERE customer_id < @var1;
  • Related