MySql DECLARE variable syntax - mysql

I am moving from SQL Server to mySQL.
MSSQL I used to write below and execute them in one go.
Declare #d datetime
Select #d='2021-02-01'
Select * from tbl where createdt>#d
This can be executed without stored procedure
Mysql:
Declare d datetime
Select d='2021-02-01'
Select * from tbl where createdt>d
How do I do this in mysql work bench? It complains syntax error in DECLARE.
I am confused about the syntax.

You can use # in MySQL too, to use a user-defined variable.
You can do it as following without using any standard procedure or functions.
set #d='2021-02-01';
select * from tbl_name where createdt> #d;
You don't need to use declare clause here.
You can refer here: Syntax reference

Related

Simple sql function with SELECT

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

Mysql select all existing tables from current database using stored procedure

I am still trying to solve this Mysql issue. I'm not a dba but need to figure out how to do it.
I need to run a select statement over all (50k) existing tables from current db.
Please note that union is not the correct way for me since I have more than 50k tables, I need to solve this with a loop.
So far, I have been trying with two approaches without success:
First: using a subquery and the information_schemma like:
Select *
from
(SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'my_db')
or
Select * from (show tables;);
Second: using a stored procedure like:
delimiter //
CREATE PROCEDURE get_all_tables()
BEGIN
DECLARE a varchar(100);
DECLARE cur1 CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'my_db';
OPEN cur1;
But neither is doing what I want.
It yields syntax or conceptual errors.
BTW: I already solve this using an external perl script performing a "show tables" and running a select withing a loop.
This is ok but I think this should be solved with pure mysql.
Any idea would be welcome.
Leo.
SELECT * FROM (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'my_db')
First of all, you can't do this in any implementation of SQL. The table name must be known by the query at prepare-time, not at run-time. You can't select from a string, you have to select from a table identifier.
It's the difference between these two queries:
SELECT * FROM MyTable -- identifier
SELECT * FROM 'MyTable' -- string value (this won't work)
By the way, most programming languages have a similar concept, of a function or class name being different from the name of that function or class. You can't execute a function by its name using the same syntax as you would execute it by its identifier.
<?php
$result = myFunction();
$result = 'myFunction'(); // nonsense
But some languages do have ways of getting around this:
<?php
$funcName = 'myFunction';
$result = $funcName();
In SQL, you can get around this limitation by using the table name as you build a new SQL query as a string. Then prepare and execute that SQL query string at runtime. This is called a dynamic SQL query.
But like the PHP example above of using a variable to store the name of the function, using dynamic SQL requires multiple steps. You can't combine the query to get your table names into the same query that uses the results.
You were on the right track with your stored procedure that opens a cursor for the set of table names. But you can't open cursors from dynamic SQL statements in stored procedures.
You can do what you need pretty easily using dynamic SQL in a scripting language like PHP or Python.

How to call a stored procedure using select statement in mysql

I have call statement like
CALL report_procedure
('2013-02-01',now(),'2015-01-01','1');
and i want to use it in a select query.
i have tried like
Select * from ( CALL report_procedure
('2013-02-01',now(),'2015-01-01','1'));
but error occurs.
like
Error Code: 1064. You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near ( CALL report_procedure
('2013-02-01',now(),'2015-01-01','1') at line 3 0.297 sec
Can anyone suggest me a method to call stored procedure in Select statement in mysql??
It is not possible to use result set from procedure in FROM clause. MySQL does not allow doing this.
You may populate another table (or temporary table) in your procedure, and after, use that table in SELECT commands -
CALL report_procedure ('2013-02-01',now(),'2015-01-01','1'); -- fill temp_table
SELECT * FROM temp_table;
--Firstly your store procedure should look something like this:
CREATE PROCEDURE report_procedure(
IN d1 DATE,
dnow DATE,
d2 DATE,
val INT
)
BEGIN SELECT *
FROM yourtablename
WHERE date1 = d1
AND datenow > dnow
AND date2 > d2
AND value = val;
END
--The store procedure contains the select statement.
-- then you can call the store procedure like that:
CALL report_procedure('2013-02-01',now(),'2015-01-01','1');
--hope it helps

how to set variables variables in mysql

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

How to use a procedure into the select and insert?

I'm work with store procedures, supose that I've the following procedure that return a value, and this value I use in other query.
CREATE PROCEUDRE filter(IN string varchar(1000), OUT salida varchar(1000))
BEGIN
.....
END
And I want make a insert with a select query for example:
INSERT INTO otherTable
SELECT filter(concat_group(column)) , value1,value2 from mytable
GROUP BY column,value,value2;
which is the correct way to do this?
Generally, you cannot call a stored procedure in the SQL select statement. What you want is like custom scalar functions.
reference
mysql scalar function with for loop