GBase 8a
运维管理
文章

获取数据库所有表记录的存储过程fnGetTablesCount

发表于2023-07-17 16:40:5161次浏览0个评论

一、项目需求:

GBase 8a MPP Cluster,获取 courseware 数据库所有表的记录行数;

二、需求分析:

information_schema.tables 确实存在 TABLE_NAME 和 TABLE_ROWS 和我们的需求很接近,但是 select TABLE_NAME 和 TABLE_ROWS from information_schema.tables where table_schema='courseware' 得到的结果却让我们失望,TABLE_ROWS 不是 0 就是空。这是 GBase 8a MPP Cluster 一种降低代价的实现方案,而不是 BUG。

三、方案设计:

使用存储过程预处理功能实现将动态表名转为数据表对象。

 

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 @sSql = concat('select count(*) into @cnt from ', tableName);
            
            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

评论

登录后才可以发表评论