[英]DB2 dynamic table name
I want to count the rows of a number of tables. 我想计算许多表格的行数。 But the table name should be used dynamically.
但是表名称应动态使用。 I want to do that within one SQL statement.
我想在一个SQL语句中执行此操作。
I tried it with 我尝试过
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
but I receive the error 但我收到错误
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
and found no other working solution... 没有找到其他可行的解决方案...
Is there a solution for that? 有解决方案吗? Thanks in advance.
提前致谢。
I assume that your SELECT COUNT(*) FROM tmp.tbl
should translate in multiple statements like 我假设您的
SELECT COUNT(*) FROM tmp.tbl
应该转换成多个语句,例如
select count(*) from TABLECD
select count(*) from TABLE2CD
...
However, your query will try to do a count of the table TBL in the schema TMP. 但是,您的查询将尝试对模式TMP中的表TBL进行计数。
You'll have to prepare the complete SQL statement, store it in a variable and pass it to the PREPARE statement ( documentation ). 您将必须准备完整的SQL语句,将其存储在变量中,并将其传递给PREPARE语句( 文档 )。
A rather complete stored procedure which somewhat fits your requirements can be found here . 您可以在这里找到一个相当完整的存储过程,该存储过程可以满足您的要求。 The result of the counts will be stored in a table
COUNTERS
which you can query afterwards. 计数结果将存储在
COUNTERS
表中,您可以在以后查询。
//edit: this is the example from the topic, adapt to work (not tested since I have no DB2 instance to test atm): // 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.