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.
Related
I have a stored procedure in MYSQL where I am passing one parameter which is passed into an SQL statement as you can see below however the result is returning a count of 0 where I am expecting a count of 2.
Stored Procedure:
CREATE DEFINER=`admin`#`%` PROCEDURE `EmployeesRecords`(IN employee_id varchar (1000))
BEGIN
--
declare v_count int ;
--
select count(*)
into v_count
from employees
where employees_id IN (employee_id);
--
END
One or many employee Id's can be passed into the parameter employee_id.
when Calling Stored Procedure like this : CALL EmployeesRecords('2,3'); This returns a count of 0 where I am expecting a count of 2
As for the parameter itself, I have tried various methods including changing it in the procedure to have it as "IN ('2','3') in the SQL condition however it still does not work.
However what I have noticed is that when passing one employee Id, it works successfully such as CALL EmployeesRecords('2');
Can anyone guide me to what I am doing wrong please?
I have a mysql cursor that is not returning any records when comparing a date variable to a date column in the table. All of this is taking place inside a stored procedure. Hence:
DECLARE StartDateInterval Date DEFAULT '1997-11-01';
DECLARE EndDateInterval Date DEFAULT '1997-12-31';
DECLARE End_Period Date DEFAULT '1997-12-31';
DECLARE prev_period_tournie_rating CURSOR FOR select PID, Rating, RD from rating where Rating_Date = End_Period;
SET End_Period = (StartDateInterval - interval 1 day);
OPEN prev_period_tournie_rating;
firstloop: LOOP
FETCH prev_period_tournie_rating INTO vPID, PrevRat, PrevRD;
IF done = 1 THEN LEAVE firstloop; END IF;
SET decayedRD = ROUND(`newRD`(PrevRD));
INSERT into rating (PID, Rating, RD, Rating_Date, Rating_Type) VALUES (vPID, PrevRat, decayedRD, EndDateInterval, 2);
END LOOP;
CLOSE prev_period_tournie_rating;
There is more code in the Stored Procedure that I have deleted. After the DECLARE statements, all of the above takes place inside a WHILE . . .END WHILE that iterates through 2 month intervals from 1997 to the present, hence the need for End_Period to be a variable and not coded to a single date.
When I remove the where condition the Cursor retrieves records from the rating table.
I do not pass End_Period as a paramater in the cursor DECLARE statement. It appears that some mysql dialects allow/require this and some don't. Even though I have tried to set my dialect to MariaDB (which does allow parameters, I get an error if I add End_Period as a parameter.
Rating_Date is a date column in the table rating, using the standard mysql format (YYYY-MM-DD).
Any help on solving this would be appreciated. This is my first attempt at using a Stored Procedure and it is proving to be a challenge!
Much appreciated if you can have a quick look on the below.
I've created the below stored function in order to format the datetime from a table to mysql format;
(%Y-%m-%d; %h:%i:%s);
Delimiter $$
create function formatdata(dataparameter varchar(20), hourparametru
varchar(20))
begin
DECLARE x time;
declare y date;
set x = (select STR_TO_DATE(Datăcolumn,'%h:%i:%s')from tabelname);
set y = (select STR_TO_DATE(oracolumn,'%Y-%m-%d')from tabelname);
select x,y;
if current_time > time(hourcolumn) then
select STR_TO_DATE(Datăcolumn,'%Y-%m-%d')into x from tabelname;
select STR_TO_DATE(oracolumn,'%h:%i:%s') into y from tabelname;
return(x,y);
end if;
end $$
Delimiter ;
What am I doing wrong here?
The error is You have an error in your sql syntax near first select_Str_to_date.
but I am kind of confused how local variables, IN parameters work together - so I am assuming that here is where I do wrong..
If you set a variable to a result of a scalar SELECT query, you put the query inside parentheses.
This:
set x = select STR_TO_DATE('07:47:20','%h:%i:%s');
Should be:
set x = (select STR_TO_DATE('07:47:20','%h:%i:%s'));
That explains the syntax error.
You also have a few other problems in this function.
Re your comment:
The line:
select x,y;
Would return a result set, but that's not allowed in a stored function (it is allowed in a stored procedure). I think you can just remove this line.
A stored function can only return a single scalar value. You should have a line RETURNS <datatype> before your BEGIN, and you should RETURN a single value somewhere in your function.
Another problem: your assignments are not valid if the table has more than one row. Setting a variable to a scalar SELECT query result is valid only if the query returns a single column and single row.
Another problem:
if current_time > time(hourcolumn) then
What is hourcolumn? It's not a function parameter or a local variable. But if it is a column of a table, there's no syntax to say which table you mean.
Another problem:
return(x,y);
You can't return a pair of variables from a stored function. Only one variable.
Another problem: The only RETURN is inside an IF block. What should the function return if the IF condition isn't true?
I am trying to create an sql trigger statement using phpmyadmin trigger interface.
Trying to do something for table 1 as shown below :
BEGIN
declare #valid_number int ;
select id into #valid_number from table 2 ;
if 10 does not exist in #valid_number then
{do something here}
end if;
END
how to achieve it?
First: a variable in a stored routine can't store multiple values, just a single one. Your statement
select id into #valid_number from table 2 ;
will only work, if the query returns exactly one row. An error will occur, if the query returns multiple rows, a warning, if the query returns no row at all, see the manual page to SELECT ... INTO:
The INTO clause can name a list of one or more variables, which can be
user-defined variables, stored procedure or function parameters, or
stored program local variables. [...]
The selected values are assigned to the variables. The number of
variables must match the number of columns. The query should return a
single row. If the query returns no rows, a warning with error code
1329 occurs (No data), and the variable values remain unchanged. If
the query returns multiple rows, error 1172 occurs (Result consisted
of more than one row).
Solution:
It's not difficult to create a statement that gives you the desired answer in exact one row, i.e.
SELECT COUNT(*) into valid_number FROM example WHERE id = 10;
This query will return 0, if the id 10 does not exists in column id and the count of occurences else. Of course there are several ways to achieve this, this is just one of them. You could rewrite your stored routine to:
BEGIN
-- prefer local variables, don't use user defined, if not needed.
DECLARE valid_number int;
SELECT COUNT(*) into valid_number FROM example WHERE id = 10;
IF valid_number = 0 THEN
-- do something here
END IF;
SELECT result;
END
Note
You could use a cursor to traverse the result of a query, but most times one wants to avoid a cursor. To use a cursor under similar conditions as of this question would not be the SQL way to do it and most times very inefficient.
I have a user defined function.
In that function I declared a variable of type datetime.
I am assigning the result of a query into this variable. And I am returning this assigned value. It looks like
delimiter$$
drop function if exists getQEDate$$
create function getQEDate() returns datetime
begin
declare qedate datetime;
select date into qedate from qenddates where ....;
return qedate;
end$$
delimiter ;
When accessing this function I am getting an exception like "returns more than a row...".
So I am thinking this error occurred while returning the result. That means the variable qedate can hold more than one row.
Is the above analysis makes sense ?
It's probably that your query is returning more than 1 row and it can't store that into a variable. If you're only expecting 1 row you should check your where clause or add LIMIT 1 to the end of the query in the function.
I'm guessing since I can't see your data or your where clause :)