mysql number of records in cursor without iterating?

北城以北 提交于 2019-12-01 00:27:20

问题


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 ?


回答1:


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 ;



回答2:


Include SQL_CALC_FOUND_ROWS in your cursor select.Then on fetch use FOUND_ROWS(). It gives the number of records



来源:https://stackoverflow.com/questions/19168327/mysql-number-of-records-in-cursor-without-iterating

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!