Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
How to know Cursor in MySQL .....
Posted
Updated 27-Jul-12 7:18am
v2
Comments
PraveenSura 27-Jul-12 13:47pm    
Declare cursorname cursor cursortype for select * from tblname

1 solution

1. Cursor declaration: To declare a cursor you must use the DECLARE statement.

Syntax:

SQL
DECLARE cursor_name cursor for select_statement;


If you want to use the multiple cursor then the cursor name must have an unique name and each cursor have specified block.

2. Cursor open statement: To open the cursor you must use the OPEN statement. If you want to fetch rows from it then you must open the cursor.

Syntax:

SQL
OPEN cursor_name;  


3. Cursor fetch statement: If you want to retrieve next row from the cursor and move the cursor to next row then you need to fetch the cursor.

Syntax:

SQL
FETCH cursor_name INTO var_name;


If a row exists, then the above statement fetches the next row and cursor pointer moves ahead to the next row. If no more data left "no data condition" with SQLSTATE value 02000 occurs.

4. Cursor close statement: This statement is used to close the opened cursor.

Syntax:

SQL
CLOSE cursor_name;  



Cursor Example:

student table:
ID	StudentName	address
1	Vinod	        Rohini,Delhi
2	Ravi	        Lucknow,Up
NULL	NULL	        NULL

Declare, open, fetch and close the Cursor:

DELIMITER //
SQL
CREATE FUNCTION student_list() RETURNS VARCHAR(255) 
   BEGIN    
   DECLARE record_not_found INTEGER DEFAULT 0; 
   DECLARE student_name VARCHAR(50) DEFAULT ""; 
   DECLARE stu_list VARCHAR(255) DEFAULT ""; 
   DECLARE my_cursor CURSOR FOR SELECT studentName FROM student;    DECLARE CONTINUE HANDLER FOR NOT FOUND SET record_not_found = 1;     
   OPEN my_cursor;    
   allStudents: LOOP 
   FETCH my_cursor INTO student_name; 
   IF record_not_found THEN 
   LEAVE allStudents; 
   END IF; 
   SET stu_list = CONCAT(stu_list,", ",student_name); 
   END LOOP allStudents;    
   CLOSE my_cursor;    
   RETURN SUBSTR(stu_list,3); 
   END 
//
DELIMITER ;
SQL
SELECT student_list() AS Cities;
DROP FUNCTION student_list;

Output:


ID	StudentName	address
1	Vinod	        Rohini,Delhi
 
Share this answer
 
Comments
Sandeep Mewara 27-Jul-12 15:32pm    
Good answer. 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900