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
It's possible to accomplish your goal by approaching it as a two-step process:
- Query the SYSCAT views to generate a separate SQL statement for each potential child table of CLIENT
- 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
;