DB2动态表名

时间:2014-06-25 11:56:03

标签: sql database db2

我想计算一些表的行数。但应该动态使用表名。我想在一个SQL语句中做到这一点。

我用

尝试了
BEGIN ATOMIC 
  FOR tmp AS (
    SELECT tabschema || '.' || tabname tbl 
    FROM syscat.tables WHERE tabname LIKE '%CD') DO 
       (SELECT COUNT(*) FROM tmp.tbl); 
  END FOR; 
END

但我收到错误

DB21034E  The command was processed as an SQL statement because it was not a 
valid Command Line Processor command.  During SQL processing it returned:
SQL0204N  "TMP.TBL" is an undefined name.  LINE NUMBER=1.  SQLSTATE=42704

并没有找到其他有效的解决方案......

有解决方案吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您的SELECT COUNT(*) FROM tmp.tbl应该在多个语句中翻译,例如

select count(*) from TABLECD
select count(*) from TABLE2CD
...

但是,您的查询将尝试对模式TMP中的表TBL进行计数。

您必须准备完整的SQL语句,将其存储在变量中并将其传递给PREPARE语句(documentation)。

可以找到一个完全符合您要求的完整存储过程here。计数结果将存储在表COUNTERS中,您可以在之后查询。

// edit:这是主题中的示例,适应工作(未经测试,因为我没有DB2实例来测试atm):

CREATE PROCEDURE tableCount()
LANGUAGE SQL
BEGIN
   DECLARE SQLCODE INTEGER DEFAULT 0;
   DECLARE SQLSTATE CHAR(5);
   DECLARE vTableName VARCHAR(20);
   DECLARE vTableCount INTEGER;
   DECLARE stmt varchar(2000);
   DECLARE not_found CONDITION FOR SQLSTATE '02000';
   DECLARE c1 CURSOR FOR
   SELECT tabname from syscat.tables where tabschema='DB2ADMIN';
   DECLARE C2 CURSOR FOR S2
   DECLARE CONTINUE HANDLER FOR not_found
   SET stmt = '';
   Delete from COUNTERS;
   OPEN c1;
   getRows:
   LOOP
     FETCH c1 INTO vTableName;
     IF SQLCODE = 0 THEN
       SET stmt ='SELECT Count(*) FROM ' ||  vTableName;
       PREPARE S2 FROM stmt;
       OPEN C2;
       SET vTableCount = 0;
       FETCH C2 INTO vTableCount;
       INSERT INTO COUNTERS (tableName, tableCount)
              VALUES (vTableName, vTableCount);
       CLOSE C2;
     ELSE
       LEAVE getRows;
     END IF;
   END LOOP getRows;
   CLOSE c1;
END