How to get a count from all table containing a specific column?

半城伤御伤魂 提交于 2019-12-13 03:42:44

问题


I have a IBM Content Manager with a DB2 database.

In ICMADMIN, I have a bunch of tables, and some of them contain a specific column (let's call it ID_CLIENT), which is an ID linking to one table (CLIENT).

How can I get the number of rows for each CLIENT from every table containing the ID_CLIENT column?


I know how to retrieve names of every table containing ID_CLIENT, but not how to join CLIENT on them dynamically.

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

(let's call this query A)

So my pseudo query would look like:

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

回答1:


It's possible to accomplish your goal by approaching it as a two-step process:

  1. Query the SYSCAT views to generate a separate SQL statement for each potential child table of CLIENT
  2. Capture and execute the SQL you generated

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 ;



来源:https://stackoverflow.com/questions/27441641/how-to-get-a-count-from-all-table-containing-a-specific-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!