代码改变世界

【DB2】 判断数据库中行数小于5000的表,并将其数据导出,然后导入新的数据库-更新

2018-11-06 10:35  Ivan的一亩三分地  阅读(517)  评论(0)    收藏  举报

方法一:

查询基于统计信息的条数

select stats_time, trim(tabschema) || '.' || trim(tabname) from syscat.tables where card < 5000 and card > 0 with ur;

 

方法二:

测试目标:

1.  检查当前数据库中,行数小于5000的表

2.  导出那些表的数据

 

实施步骤:

1.  创建存储表名的表

create table checktab(tabname varchar(60) not null primary key)@

 

2.  存储过程检查行数小于5000的表,并将表名存放到临时表中

--drop the table check_table if existed

drop procedure check_table@

 

--check the table whose number of  rows are less than 5000

CREATE PROCEDURE check_table() 
LANGUAGE SQL
P1: BEGIN
DECLARE p_tab varchar(60);
DECLARE p_count INTEGER;
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE stmt1 varchar(1024);
DECLARE stmt2 varchar(1024);
DECLARE c CURSOR FOR select trim(tabschema) || '.' || trim(tabname) from syscat.tables where tabschema not in ('SYSCAT','SYSSTAT','SYSTOOLS','SYSIBMADM','SYSIBM','SYSPUBLIC');
DECLARE c1 CURSOR FOR v_stmt1;

OPEN c;

FETCH FROM c INTO p_tab;

WHILE(SQLSTATE = '00000') DO

set stmt1 = 'select count(1) from ' || p_tab || ' with ur';
prepare v_stmt1 from stmt1;
open c1;
fetch from c1 into p_count;
close c1;
if ( p_count < 5000 and p_count  > 0 )
then
insert into checktab values (p_tab);
end if;
FETCH FROM c INTO p_tab; 
END WHILE;

CLOSE c;

END P1
@

 

3.  生成导出语句

 db2 -x "select 'export  to  ' || trim(tabname) || '.ixf  of ixf  select * from ' || tabname || 'with ur;'  from  checktab" > export.sql

4.  导出数据

db2 connect to <db-name>

db2 -tvf  export.sql -z export.out

 

5.  生成导入语句

 db2 -x "select 'import   from  ' || trim(tabname) || '.ixf  of ixf  insert into ' || tabname || ';'  from  checktab" > import.sql

 

6.  将包上传到新的服务器上,导入数据

db2 connect to <db-name>

db2 -tvf  import.sql   -z import.out

 

DB2存储过程开发注意事项:

1. DB2 如何引入变量,在语句中,如何使用变量

2. 如何通过命令,创建存储过程

    1) 要有明确的terminator符号,不建议使用默认的‘;’ 比如“@”,db2 -td@ -vf   t2.sql   -z t2.out

    2) 对于表名是变量的情况下,如何执行

    select count(1) into  var_parm1 from  var_parm2;

    这里的实现进行了分解:

动态语句拼接表名

将结果保存到cursor

-- define cursor

DECLARE p_count INTEGER;

DECLARE stmt1 varchar(1024);

DECLARE c1 CURSOR FOR v_stmt1;   

--
set stmt1 = 'select count(1) from ' || p_tab || ' with ur';
prepare v_stmt1 from stmt1;
open c1;
fetch from c1 into p_count;
close c1;