I tried setting a variable in sql as follows:
DECLARE #fromDate VARCHAR(60);
SET #fromDate = '2013-01-01 00:00:00';
SET #toDate = '2013-02-01 00:00:00';
SELECT #fromDate;
but this is not working.
what am I doing incorrectly?
You don't DECLARE variables that start with #.
MySQL has two different types of variables. One is a session variable, with the # prefix. The other type is the local variable inside a trigger or stored proc.
The DECLARE statement is valid only inside of body of stored procedure or function, and this variables don't start by #.
The variables that start with # don't need DECLARE, just use outside of stored procedure inclusive.
First lets take a look at how can we define a variable in mysql
To define a varible in mysql it should start with '#' like #{variable_name} and this '{variable_name}', we can replace it with our variable name.
Now, how to assign a value in a variable in mysql. For this we have many ways to do that
Using keyword 'SET'.
Example :- mysql > SET #a = 1;
Without using keyword 'SET' and using ':='.
Example:- mysql > #a:=1;
By using 'SELECT' statement.
Example:- mysql > select 1 into #a;
Here #a is user defined variable and 1 is going to be assigned in #a.
Now how to get or select the value of #{variable_name}.
we can use select statement like
Example :-
mysql > select #a;
it will show the output and show the value of #a.
Now how to assign a value from a table in a variable.
For this we can use two statement like :-
#a := (select emp_name from employee where emp_id = 1);
select emp_name into #a from employee where emp_id = 1;
Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.
refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql
Related
I have a sproc with multiple selects and result sets. The last query in the sproc needs to select data where a table created date >= the first day of the current month. I have SQL which successfully returns the first day of the month as expected. I need to select this value into a sproc variable FirstDayOfTheMonth and then reference this variable in the WHERE clause of the subsequent SELECT statement in the sproc. I included the following SQL before the final result set in the sproc but it seems that MySQL doesn't like something about it - something about its structure, positioning or syntax:
DECLARE FirstDayOfMonth INT DEFAULT 0;
SET FirstDayOfMonth = (SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))- 1 DAY)
How can I update my existing attempt at a MySQL sproc variable so that my sproc compiles successfully with this variable declaration?
UPDATE
I tried to put the following 2 lines immediately after the BEGIN keyword in my sproc:
DECLARE FirstDayOfMonth INT DEFAULT 0;
SET FirstDayOfMonth = (SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))- 1 DAY)
MySQL Workbench displays an error on the SET statement:
FirstDayOfMonth is not valid at this position, expecting an identifier
Any idea what I need to do differently here?
The DECLARE-statements need to be in the beginning of the procedure, before anything else, just after the BEGIN.
I can assign value to variable and select column in single statement in MySQL like this
declare #i int= 0
select #i :=1 , col1 FROM Table
But can not do that in SQL SERVER.
As it gives the error
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
Please describe what is the underlying difference.
I need to run following query in my stored function with variables
SELECT json_unquote(json_extract(value,'$."_key"')) INTO org_rank_value FROM preferences WHERE id=_id;
Here _key and _id are declared variables, but _key is not replaced with value since it is in quotes. Is there any way to build and execute above query?
Without more context about your database structure, this is how i interpreted your question.
1) you want to select a specific ID.
2) you want to change a parameter within your json-field based off of the ID.
3) you want to execute the query.
DECLARE #json NVARCHAR(MAX) = (SELECT org_rank_value FROM preferences WHERE id=_id)
SELECT * FROM OPENJSON(#json)
WITH (
yourKey varchar(200) '$.key' -- change to whatever your variables are.
) AS changeKey;
UPDATE preferences SET json_unquote(json_extract(value,'$."_key"')) INTO org_rank_value WHERE id=_id;
In MySQL, u can use
JSON_ARRAY_APPEND
I have a trigger like this:
IF ( value > new.value ) THEN
...
END IF
It will be executed AFTER INSERT. I need to pass value (it is a number) while inserting because of using it into the condition of the trigger. Any idea how can I pass it?
Noted that, currently it is hardcoded into trigger like IF ( 5 > new.value ) THEN. And all I'm trying to do is passing that 5 dynamically while inserting.
No, there's no defined mechanism for passing an argument to a TRIGGER.
The only things I can think of is a user-defined variable (but I wouldn't really want to go there), or a SELECT statement to retrieve the value from a table.
We can set a user-defined variable in our session:
SET #value_for_after_insert_trigger = 5 ;
Then perform an INSERT
INSERT INTO mytable (...) VALUES (...)
when the AFTER INSERT trigger is fired (for each row), the trigger body can reference a user-defined variable. For example:
DECLARE ln_value INTEGER;
SET ln_value = #value_for_after_insert_trigger;
Then we can do
IF ( ln_value > NEW.value ) THEN
Note that we aren't guaranteed that some other statement in our session won't modify our user-defined variable. For example, a BEFORE INSERT trigger might execute a statement such as:
SET #value_for_after_insert_trigger = 42 ;
... overwriting the value that was previously stored. The AFTER INSERT trigger would read the currently assigned value, getting the 42, not the 5 we specified earlier. And we aren't guaranteed that the AFTER INSERT trigger won't perform some action that modifies the value.
SET #value_for_after_insert_trigger = #value_for_after_insert_trigger + 1;
affecting the trigger execution for subsequent rows.
I do not advocate this as a design. I would avoid using user-defined variables like this.
Another alternative would be to use a SELECT statement to query the value from a table.
I try to understand how functions work. I can make the equivalent in procedure but I can't create a simple function with select.
element is UNIQUE and
thing is PRIMARY
CREATE DEFINER=`root`#`localhost`
FUNCTION `get_element_by_thing`(`thing` VARCHAR(255))
RETURNS VARCHAR(255)
CHARSET utf8
NOT DETERMINISTIC
READS SQL DATA
SQL SECURITY DEFINER
DECLARE #return_element VARCHAR(255);
SET #return_element = (
SELECT
`element`
FROM
`table1`
WHERE
`thing` = thing
);
RETURN #return_element;
I use the phpmyadmin interface.
1) Don't declare user-defined variables.
The name of a local variable in MySQL stored program does not start with an at sign #. As an example:
DECLARE stored_program_local_variable VARCHAR(255);
SET stored_program_local_variable = 'somevalue';
The name of a user-defined variables start with an at sign #. (The at sign character is what distinguishes user-defined variables from other identifiers.) It's not valid to declare a user-defined variable in a stored program. To create a user-defined variable, just assign a value to it. For example:
SET #user_defined_variable = 'somevalue';
2) If we don't need to persist variables beyond the scope of a stored program, we typically use local variables, which exist only for the duration of the stored program execution. (Which is different behavior than user-defined variables which are at the session level.)
3) Use the SELECT ... INTO syntax to retrieve scalar values into user-defined or local variables. https://dev.mysql.com/doc/refman/5.7/en/select-into.html
Try:
DELIMITER $$
CREATE DEFINER=`root`#`localhost`
FUNCTION `get_element_by_thing`(`thing` VARCHAR(255))
RETURNS VARCHAR(255)
...
BEGIN
DECLARE return_element VARCHAR(255) ;
SELECT t1.element
INTO return_element
FROM table1 t1
WHERE t1.thing = thing
LIMIT 1 ;
RETURN return_element ;
END $$
DELIMITER ;
Note: with ambiguous identifiers (i.e. routine parameter and column with the same name in a SQL statement, the routine parameter takes precedence over the column name. Qualify the column reference with the table name or table alias so it's not ambiguous. I prefer to assign routine parameters (and local variables) names that do not match column names.
If for some reason you need to assign a value to a user-defined variable in a SQL statement, you can use the := assignment operator. This is also valid outside the context of a stored program.
SELECT #user_defined_variable := t.somecolumn
FROM mytable t
WHERE somecondition
ORDER BY someexpression
LIMIT 1