Tuesday, 6 April 2021

MYSQL Variable assignment

 

MySQL variable assignment

There are two ways to assign a value to a user-defined variable.

The first way is to use the SET statement as follows:

SET @variable_name := value;
Code language: SQL (Structured Query Language) (sql)

You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter.

SET @counter := 100;
Code language: SQL (Structured Query Language) (sql)

The second way to assign a value to a variable is to use the SELECT statement. In this case, you must use the := assignment operator because, within the SELECT statement, MySQL treats the = operator as the equal operator.

SELECT @variable_name := value;
https://www.mysqltutorial.org/mysql-variables/#:~:text=There%20are%20two%20ways%20to,to%20a%20user%2Ddefined%20variable.&text=You%20can%20use%20either%20%3A%3D,100%20to%20the%20variable%20%40counter.&text=The%20second%20way%20to%20assign,to%20use%20the%20SELECT%20statementMYSQL cant assign multiple values to variable https://stackoverflow.com/questions/3156481/multiple-values-in-mysql-variableThe best way to acheive

You cannot (as far as I am aware) store multiple values in a MySQL user defined variable. What you have done is create a string which contains:

'20100630', '20100701'

That is not two separate values, but a single string value, just as this is a single string value:

SET @a := "It's a single string, and that's the problem";

You need to use two separate variables, or prepare a statement, like this:

SET @a := "20100630";
SET @b := "20100701";

SET @sql = CONCAT(
    'SELECT * FROM wordbase WHERE verified IN (',
    @a,
    ',',
    @b,
    ')'
);


SELECT @sql;
+--------------------------------------------------------------+
| @sql                                                         |
+--------------------------------------------------------------+
| SELECT * FROM wordbase WHERE verified IN (20100630,20100701) |
+--------------------------------------------------------------+

PREPARE stmt FROM @sql;
EXECUTE stmt;




No comments:

Post a Comment