如何从包含特定列的所有表中获取计数?

时间:2014-12-12 10:29:17

标签: sql db2 db2-content-manager

我有一个带有DB2数据库的IBM Content Manager。

在ICMADMIN中,我有一堆表,其中一些包含一个特定的列(让我们称之为ID_CLIENT),这是一个链接到一个表(CLIENT)的ID。

如何从包含ID_CLIENT列的每个表中获取每个CLIENT的行数?


我知道如何检索包含ID_CLIENT的每个表的名称,但不知道如何动态地加入CLIENT。

select tabname from syscat.columns where colname='ID_CLIENT'

(让我们调用此查询A)

所以我的伪查询看起来像:

select count(*) from CLIENT join (A) on CLIENT.ID_CLIENT = (A).ID_CLIENT

1 个答案:

答案 0 :(得分:1)

通过将其作为一个两步过程来实现您的目标是可能的:

  1. 查询SYSCAT视图,为CLIENT
  2. 的每个潜在子表生成单独的SQL语句
  3. 捕获并执行您生成的SQL
  4. WITH ctbls ( tbl ) AS ( SELECT RTRIM( c.tabschema ) || '.' || c.tabname FROM syscat.columns c INNER JOIN syscat.tables t ON t.tabschema = c.tabschema AND t.tabname = c.tabname WHERE c.colname = 'CLIENT_ID' AND c.tabname <> 'CLIENT' -- we don't want to join CLIENT to itself AND t.type = 'T' -- if you want to work with tables only AND c.typename = 'INTEGER' -- if you want only want CLIENT_ID columns of a certain type ) -- Construct a left join between CLIENT and each table returned by the CTE above SELECT 'SELECT ''' || tbl || ''' AS childtablename, par.client_id, COUNT(*) AS childrows ' || 'FROM client par LEFT OUTER JOIN ' || tbl || ' chd ' || 'ON chd.client_id = par.client_id GROUP BY par.client_id;' FROM ctbls ;