How can I declare a variable for a normal query in MySQL?
e.g.,
declare @myVar date; set @myVar = something; select * from someTable where someColumn = @myVar;
I tried and the syntax seems to be wrong...what am I missing?
You can declare a variable using @anyVariablename which is a session variable. To create a session variable, you need to use SET command.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
You can declare a session variable in this way :
SET @myvarname := 'value';
or a local variable in this way :
DECLARE my_variable varchar(30)
also:
DECLARE my_variable varchar(30) DEFAULT 'value'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With