MySQL cursor avg() fetch null - mysql

I have a computed column in cursor select query.
drop procedure if exists update_avg;
delimiter $$
create procedure update_avg()
BEGIN
declare score decimal(9,4);
declare id varchar(5);
declare done bool default false;
declare c_update cursor for
select stu_id, avg(score) from chooses group by stu_id;
declare continue HANDLER for not found set done = true;
open c_update;
fetch c_update into id, score;
select id, score; -- test purpose
while(not done) do
update student set average_score = score where student_id = id;
fetch c_update into id, score;
end while;
close c_update;
END
delimiter ;
call update_avg();
When I execute this query it works fine:
select stu_id, avg(score) from chooses group by stu_id;
|stu_id|avg(score)|
|------|----------|
|1 | 73.5000|
|10 | 93.0000|
|11 | 53.0000|
...
And when I call update_avg(); output:
|id|score|
|--|-----|
|1 |NULL |
My question is why this cursor cannot fetch avg(score) from select query and how to fix this.

This operation does not require cursor and could be done using correlated subquery:
update student
set average_score = (SELECT AVG(score)
FROM chooses
WHERE chooses.stu_id = student.student_id)
-- WHERE EXISTS (SELECT 1 FROM chooses WHERE chooses.stu_id = student.student_id)
-- this condition is to avoid updating rows
-- that do not have corresponding rows in chooses table

Related

How to reference an input in SQL functions?

I have a table like this:
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
I am writing a function with mySQL to get the n th largest value in Salary.
Here is the function:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 offset (N - 1)
#FETCH NEXT 1 ROWS ONLY
);
END
But I got the an error near (N-1).
if I change (N-1) to 1 :
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 offset 1
#FETCH NEXT 1 ROWS ONLY
);
END
It runs correctly.
So the question is how to reference input in SQL function? It seems it can be directly called as an argument as we do in other languages.
LIMIT argument cannot be a variable. Use prepared statement - in it the LIMIT parameter may be taken from a variable. But dynamic SQL is not allowed in the function - use stored procedure:
CREATE PROCEDURE getNthHighestSalary(N INT)
BEGIN
SET #sql := 'SELECT DISTINCT Salary
INTO #output
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET ?';
PREPARE stmt FROM #sql;
SET #output := N-1;
EXECUTE stmt USING #output;
DROP PREPARE stmt;
SELECT #output;
END
fiddle
It seems I need to declare and set a variable before reference it in SQL query:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
RETURN (
# Write your MySQL query statement below.
select DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET M
#FETCH NEXT 1 ROWS ONLY
);
END

SQL query for insertion multiple data using for loop

My data set
Tabel Name Users
unique_id uid
123487.1 1000
123488.1
123489.1
123490.1
As shown above this is my existing data and i want to add uid, so my data should be displayed as shown below.
unique_id uid
123487.1 1000
123488.1 1001
123489.1 1002
123490.1 1003
You don't need cursors for this. Just do an update:
select #u := max(user_id)
from users;
update users
set user_id = (#u := #u + 1)
where user_id is null
order by unique_id;
Providing that uid value is the only a single value in your data set, you can use that simple query:
select unique_id, first_value(uid) over(order by unique_id) + row_number() over(order by unique_id) - 1 fv from users;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=d8102c3ef394d304eefa9d42b5a479ba
Best regards.
You can create a procedure like this:
CREATE PROCEDURE uid_update()
BEGIN
DECLARE Done_c INT;
DECLARE v_min_id INT;
declare number_plus int;
declare v_cur int;
DECLARE curs CURSOR FOR
select ROW_NUMBER() OVER (order by unique_id) rn
from testTable
where uid is null;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET Done_c = 1;
SELECT max(uid) INTO number_plus FROM testTable;
OPEN curs;
SET Done_c = 0;
REPEAT
FETCH curs INTO v_cur;
select min(unique_id) into v_min_id
from testTable
where uid is null;
update testTable
set uid = number_plus + v_cur
where uid is null
and unique_id = v_min_id ;
commit;
UNTIL Done_c END REPEAT;
CLOSE curs;
END
And then call that procedure like this:
call uid_update;
The values will then be updated as you asked for.
Here is the DEMO.

Stored Procedure to Update Records by based on the values of other table in loop

I have two tables.
Table A
-------------------------------------------
id | date | shiftId | activityId |
-------------------------------------------
1 2018-09-09 1 100
2 2018-09-09 1 101
Table B
------------------------------------------------------------------
id | reading | resourceId |date | shiftId | activityId
------------------------------------------------------------------
1 10.0 10 2018-09-09 1
2 11.0 11 2018-09-09 1
Now, I want to update Table B activityId from Table A, querying Table A on shiftid and shiftDate.
How to write stored Procedure to update Table B in loop?
I tried below query.
create or replace FUNCTION Update_TableB_ActivityId()
Returns Void as $$
Declare
rec RECORD;
query text;
activityId integer;
BEGIN
query := 'select * from TableB where "activityId" is null;
FOR rec IN execute query
LOOP
execute 'select "activityId" from TableB where "date"=rec."date"' into activityId;
execute 'Update TableB set "activityId"=activityId where "id"=rec."id"';
END LOOP;
END;
$$ LANGUAGE plpgsql;
Use update with join, so not required stored procedure for loop
For mysql:
UPDATE tableb
JOIN tablea on tablea.shiftid=tableb.shiftid and
tablea.date=tableb.date
SET tableb.activityid=tablea.activityid
For postgres:
UPDATE tableB
SET tableb.activityid=tablea.activityid
FROM tableA
WHERE tableA.shiftid=tableB.shiftid and
tableA.date=tableB.date;
This is POSTGRESQL STORED PROCEDURE
CREATE OR REPLACE FUNCTION schemaName.updateactivityid()
RETURNS text AS
$BODY$
declare
c_shiftId int;
c_activityId int;
c_date date;
_curs cursor FOR select distinct shiftId,activityId,date from schemaName.TableA; ----Cursor
BEGIN
OPEN _curs ; --- Opening Cursor
LOOP
FETCH _curs INTO c_shiftId,c_activityId,c_date;
--- Fetching Cursor Data into Variables
EXIT WHEN NOT FOUND;
RAISE NOTICE 'shiftid %%%',c_shiftId;
RAISE NOTICE 'activityid %%%',c_activityId;
RAISE NOTICE 'date%%%',c_date;
Update table schemaName.TableB SET TableB.activityId=c_activityId where TableB.date=c_date and TableB.shiftId=c_shiftId; ---Update Statement
END LOOP;
Close _curs;
Return 'Y';
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION schemaName.updateactivityid()
OWNER TO postgres;

Select Inside Insert Statement - MySQL Cursors

I tried some, but I couldn't find the solution, somehow I managed to get this result.
Here is the query:
DELIMITER ##
CREATE PROCEDURE test1(start_date DATE,end_date DATE)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE a INT;
DECLARE present INT;
DECLARE total INT;
-- Declare the cursor
DECLARE id CURSOR
FOR
SELECT staff_id FROM ost_staff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Open the cursor
DROP TEMPORARY TABLE IF EXISTS reports;
CREATE TEMPORARY TABLE IF NOT EXISTS reports
(
staff_id INT(10),
present INT(10),
total INT(10)
);
OPEN id;
read_loop: LOOP
FETCH id INTO a;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO reports(staff_id,present,total)
SELECT (COUNT(I.interval_start)) AS present, DATEDIFF(DATE_ADD(end_date,INTERVAL 1 DAY),start_date) AS total
FROM effort_frequency E
RIGHT OUTER JOIN time_intervals I ON I.interval_start = E.log_date
AND E.staffid=a AND E.log_date BETWEEN start_date AND end_date
LEFT OUTER JOIN ost_holidays H ON H.holiday_date = I.interval_start
WHERE DATE_FORMAT(I.interval_start,'%a') = 'Sun' OR H.holiday_date = I.interval_start OR E.total_effortspent IS NOT NULL;
-- Close the cursor
END LOOP;
CLOSE id;
END ##
I got the below result:
+----------+-----------------+
| staff_id | present | total |
+----------+---------+-------+
| (NULL) | 23 | 24 |
| (NULL) | 22 | 24 |
+----------+---------+-------+
I'm getting (NULL) for staff_id, How can I get the staff_id's there ?
I tried using declared variable 'a' in insert statement, but at that time I got only staff_id, I didn't get the other 2 fields, I can't get the staff_id from the select inside insert statement coz there is some problem.
Now what i need is I need to insert the staff_id from the variable 'a' into that temporary table.
note: I'm really new to this stored procedure, but somehow managed till here, Its good if I get some detail on how to use the Select inside Insert including the solution for this.
Try this -
SELECT a, (COUNT(I.interval_start)) AS present, DATEDIFF(DATE_ADD(end_date,INTERVAL 1 DAY),start_date) AS total
Your INSERT requires three fields, but your SELECT statement only selects two: present and total .
Try:
SELECT E.staffid, (COUNT(I.interval_start))
AS present, DATEDIFF(DATE_ADD(end_date,INTERVAL 1 DAY),start_date) AS total

MYSQL stored procedure select statement select incorrect ID

I am not the most knowledge able person when it comes to stored procedures, and this problem is blowing my mind!
Basically I am just trying to run a simple update statement, but the user's ID that I am selecting to update the row is not correct when I run it in the procedure, but if I run the same select statement outside the procedure it returns the expected results.
DELIMITER $$
CREATE PROCEDURE catchUpBbs_Users()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE deleteUser, keepUser VARCHAR(255);
DECLARE id INT;
DECLARE cur1 CURSOR FOR SELECT u.username, b.username, b.id from users u RIGHT JOIN bbs_users b ON u.username = b.username WHERE u.username IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
allusers: LOOP
FETCH cur1 INTO keepUser, deleteUser, id;
IF done THEN
LEAVE allusers;
END IF;
IF deleteUser != 'anonymous' THEN
-- This is where the problems start
-- Just for test purposes, returns correct id and username
SELECT id, username FROM bbs_users WHERE username = deleteUser;
-- Just for test purposes, return INCORRECT id, but the CORRECT username
SELECT id, username FROM bbs_users WHERE username = 'anonymous';
-- The update statement that does not work as I want it to, sets the user_id to be what it already it, so no updates occur
UPDATE bbs_posts SET user_id = (SELECT id FROM bbs_users WHERE username = 'anonymous') WHERE user_id = (SELECT id FROM bbs_users WHERE username = deleteUser);
-- delete the user from the bbs_users table
DELETE FROM bbs_users WHERE username = deleteUser;
END IF;
END LOOP allusers;
CLOSE cur1;
END;
$$
DELIMITER ;
When I call the procedure the two test select statements return:
1) These results are both correct
SELECT id, username FROM bbs_users WHERE username = deleteUser;
+------+----------+
| id | username |
+------+----------+
| 13 | deleteme |
+------+----------+
2) The ID is incorrect, but the username is incorrect, the ID should be 1
SELECT id, username FROM bbs_users WHERE username = 'anonymous';
+------+-----------+
| id | username |
+------+-----------+
| 13 | anonymous |
+------+-----------+
When I run the same, minus the variable, select statements outside the procedure both return the correct results
1) These results are both correct
SELECT id, username FROM bbs_users WHERE username = 'deleteme';
+----+----------+
| id | username |
+----+----------+
| 13 | deleteme |
+----+----------+
2) These results are both correct
SELECT id, username FROM bbs_users WHERE username = 'anonymous';
+----+-----------+
| id | username |
+----+-----------+
| 1 | anonymous |
+----+-----------+
What am I doing wrong? Is there something that I missed when it comes to selects and variables when using a stored procedure?
Any help or advice would be much appreciated
The issue is that you have a scalar variable called id defined in your cursor and you are selecting into it, so both of your select statements inside of the cursor are using that stored scalar value for all references to id.
In order to get the "correct" value, you'll need to remove all ambiguity:
-- Just for test purposes, returns correct id and username
SELECT b.id, b.username FROM bbs_users b WHERE b.username = deleteUser;
-- Just for test purposes, return INCORRECT id, but the CORRECT username
SELECT b.id, b.username FROM bbs_users b WHERE b.username = 'anonymous';
have you tryed repeat the sentence "FETCH cur1 INTO keepUser, deleteUser, id" after end if and before end loop...
Does the following work any better. Have cleaned up the locations where you're effectively doing the same query multiple times. Sorry if I've misunderstood the problem - but if I've understood correctly then the query below should operate a bit more efficiently. Also removes all ambiguous field names.
DELIMITER $$
CREATE PROCEDURE catchUpBbs_Users()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE oldID INT;
DECLARE newID INT;
DECLARE cur1 CURSOR FOR
SELECT b.id
FROM users u
RIGHT JOIN bbs_users b
ON u.username = b.username
WHERE u.username IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
// Get the new id
SELECT id INTO newID FROM bbs_users WHERE username = 'anonymous';
OPEN cur1;
allusers: LOOP
FETCH cur1 INTO oldID; // b.id
IF done THEN
LEAVE allusers;
END IF;
IF deleteUser != 'anonymous' THEN
-- Just for test purposes, returns correct id and username
SELECT id, username FROM bbs_users WHERE id = oldID;
-- Just for test purposes, return INCORRECT id, but the CORRECT username
SELECT id, username FROM bbs_users WHERE id = newID;
UPDATE bbs_posts SET user_id = newID WHERE user_id = oldID;
-- delete the user from the bbs_users table
DELETE FROM bbs_users WHERE id = oldID;
END IF;
END LOOP allusers;
CLOSE cur1;
END;
$$
DELIMITER ;