A simple application of a cursor. : Fetch « Cursor « SQL / MySQL






A simple application of a cursor.

     

mysql>
mysql>
mysql>
mysql> CREATE TABLE titles (
    ->   titleID int(11),
    ->   title varchar(100),
    ->   subtitle varchar(100),
    ->   edition tinyint(4),
    ->   publID int(11),
    ->   catID int(11),
    ->   langID int(11),
    ->   year int(11),
    ->   isbn varchar(20),
    ->   comment varchar(255),
    ->   ts timestamp,
    ->   authors varchar(255),
    ->   PRIMARY KEY  (titleID)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql>
mysql>
mysql> INSERT INTO titles VALUES (1,'Linux','Installation',5,1,57,2,2000,NULL,NULL,'2005-02-28 13:34:21','Michael'),
    ->                           (2,'Excel',NULL,NULL,2,3,NULL,2000,NULL,NULL,'2005-02-28 13:34:22','David'),
    ->                           (3,'XML',NULL,NULL,1,2,NULL,1997,NULL,NULL,'2005-02-28 13:34:22','Edwards'),
    ->                           (4,'PHP',NULL,NULL,3,6,NULL,2000,NULL,NULL,'2005-02-28 13:34:22','Tom'),
    ->                           (5,'MySQL','',0,3,34,NULL,2000,'','','2005-02-28 13:34:22','Paul'),
    ->                           (6,'Java',NULL,NULL,4,34,NULL,1999,NULL,NULL,'2005-02-28 13:34:22','Tim');
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql>
mysql>
mysql>
mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE cursortest(OUT avg_len DOUBLE)
    -> BEGIN
    ->     DECLARE t, subt VARCHAR(100);
    ->     DECLARE done INT DEFAULT 0;
    ->     DECLARE n BIGINT DEFAULT 0;
    ->     DECLARE cnt INT;
    ->     DECLARE mycursor CURSOR FOR
    ->
    ->     SELECT title, subtitle FROM titles;
    ->
    ->     DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
    ->
    ->     SELECT COUNT(*) FROM titles INTO cnt;
    ->     OPEN mycursor;
    ->     myloop: LOOP
    ->        FETCH mycursor INTO t, subt;
    ->        IF done=1 THEN LEAVE myloop;
    ->        END IF;
    ->           SET n = n + CHAR_LENGTH(t);
    ->        IF NOT ISNULL(subt) THEN
    ->           SET n = n + CHAR_LENGTH(subt);
    ->        END IF;
    ->     END LOOP myloop;
    ->     SET avg_len = n/cnt;
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter ;
mysql>
mysql>
mysql> CALL cursortest(@result);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @result;
+-------------+
| @result     |
+-------------+
| 6.166666666 |
+-------------+
1 row in set (0.00 sec)

mysql>
mysql>
mysql> drop table titles;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql>

   
    
    
    
    
  








Related examples in the same category

1.FETCH Statement
2.Fetch a cursor
3.Leave a cursor fetch
4.Using while loop to loop through a cursor
5.Using loop and Fetch to read the data in a cursor
6.Output data in a cursor
7.Insert data from a cursor