Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql number of records in cursor without iterating?

I am trying to write mysql procedure for below logic,

select id, fullname from users where fullname like concat(lastname, ' ', firstname, ' (' , middlename, '%');

if above query returns 0 records then

    select id, fullname from users where fullname like concat(lastname, ' ', firstname, '%');

.... few more queries depending upon result,

I am trying to write procedure mysql procedure , in that, I am using mysql cursor,

DECLARE user_cnt CURSOR FOR select id, fullname from users where fullname like concat(lastname, ' ', firstname, ' (' , middlename, '%'); 

now I want to check number of records in user_cursor so that I can check the condition "if query returns 0 records then"

How can I find the number of records in mysql cursor without iterating on it ?

like image 320
vishal Avatar asked Oct 03 '13 20:10

vishal


1 Answers

Do a count before the cursor:

select count(*)
into @user_cnt
from users
where fullname like concat (
    lastname,
    ' ',
    firstname,
    ' (',
    middlename,
    '%'
    );

EDIT: If you want to do it after OPENING the cursor, try doing:

OPEN your_cursor;
select FOUND_ROWS() into user_cnt ;
like image 70
Filipe Silva Avatar answered Oct 28 '22 08:10

Filipe Silva