Introduction
Cursors let you look at each row in a table one by one. This helps when you want to do something with each row separately.
Cursors let you look at each row in a table one by one. This helps when you want to do something with each row separately.
DECLARE cursor_name CURSOR FOR select_statement; OPEN cursor_name; FETCH cursor_name INTO variable_list; -- process data CLOSE cursor_name;
DECLARE user_cursor CURSOR FOR SELECT id, name FROM users;
OPEN user_cursor;
FETCH user_cursor INTO user_id, user_name;CLOSE user_cursor;
This procedure uses a cursor to go through each user in the users table. For each user, it shows their ID and name.
DELIMITER $$ CREATE PROCEDURE process_users() BEGIN DECLARE done INT DEFAULT FALSE; DECLARE u_id INT; DECLARE u_name VARCHAR(100); DECLARE user_cursor CURSOR FOR SELECT id, name FROM users; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN user_cursor; read_loop: LOOP FETCH user_cursor INTO u_id, u_name; IF done THEN LEAVE read_loop; END IF; -- For example, print user info (simulate with SELECT) SELECT CONCAT('User ID: ', u_id, ', Name: ', u_name) AS user_info; END LOOP; CLOSE user_cursor; END$$ DELIMITER ; CALL process_users();
Always declare a handler for NOT FOUND to know when the cursor has no more rows.
Cursors are slower than set-based queries, so use them only when needed.
Cursors let you handle rows one by one.
Declare, open, fetch, and close a cursor in that order.
Use a handler to detect when no more rows are left.
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT id FROM users;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @user_id;
IF done THEN
LEAVE read_loop;
END IF;
SELECT @user_id;
END LOOP;
CLOSE cur;DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT name FROM employees;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @emp_name;
IF done THEN
LEAVE read_loop;
END IF;
SELECT @emp_name;
END LOOP;
CLOSE cur;DECLARE done INT DEFAULT FALSE;
DECLARE total_salary DECIMAL(10,2) DEFAULT 0;
DECLARE cur CURSOR FOR SELECT salary FROM employees;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @sal;
IF done THEN
LEAVE read_loop;
END IF;
SET total_salary = total_salary + @sal;
END LOOP;
CLOSE cur;
SELECT total_salary;Pass the test and this pattern moves unknown