GBase 8a
运维管理
文章

批量获取一个数据库中所有表记录数的存储过程

发表于2023-07-14 17:56:5941次浏览0个评论

CREATE PROCEDURE "fnGetTablesCount"()
BEGIN
    declare tableName varchar(50);
    DECLARE DONE INT DEFAULT(0);

    declare curTab cursor for select table_name from information_schema.tables where table_schema='courseware';
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

    drop table if exists tabcount;
    create temporary table tabcount(tabname varchar(50), rowcnt int);
    
    open curTab;
    repeat    
        fetch curTab into tableName;
            if not DONE then
            #set tableName = 'student';
            set @sSql = concat('select count(*) into @cnt from ', tableName);
            #select sSql;
            prepare stmt from @sSql; # 预处理声明中必须用 Session 变量
            execute stmt;# into cnt;
            #select tableName || ' 行数:' || @cnt;
            insert into tabcount values(tableName, @cnt);
            #select found_rows() '行数';
            DEALLOCATE prepare stmt;
        end if;
    UNTIL DONE END REPEAT;
        
    close curTab;
    
    select * from tabcount;
    drop table if exists tabcount;
END

评论

登录后才可以发表评论