IBM DB2 Query Toolbox - List tables with their primary keys (PKs) in Db2 database



Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

IBM Db2 Query Toolbox - List tables with their primary keys (PKs) in Db2 database

A consulta abaixo lista as tabelas e seus nomes de restrição de chave primária ( PK ).
Ao navegar na lista, você pode identificar quais tabelas têm e quais não têm chaves primárias.

Query below lists tables and their primary key (PK) constraint names.
By browsing list you can spot which tables have and which don't have primary keys.

Consulta - Query

SELECT TAB.TABSCHEMA   AS SCHEMA_NAME
,      TAB.TABNAME     AS TABLE_NAME
,      CONST.CONSTNAME AS PK_NAME
,      LISTAGG(KEY.COLNAME, ', ') 
               WITHIN GROUP(ORDER BY KEY.COLSEQ) AS COLUMN_NAME
  FROM SYSCAT.TABLES TAB
       LEFT OUTER JOIN SYSCAT.TABCONST CONST 
               ON CONST.TABSCHEMA = TAB.TABSCHEMA 
              AND CONST.TABNAME = TAB.TABNAME AND CONST.TYPE = 'P'
      LEFT OUTER JOIN SYSCAT.KEYCOLUSE KEY 
              ON CONST.TABSCHEMA = KEY.TABSCHEMA 
             AND CONST.TABNAME = KEY.TABNAME
             AND CONST.CONSTNAME = KEY.CONSTNAME     
 WHERE TAB.TYPE = 'T'
   AND TAB.TABSCHEMA NOT LIKE 'SYS%'
 GROUP BY TAB.TABSCHEMA
 ,        CONST.CONSTNAME
 ,        TAB.TABNAME   
 ORDER BY TAB.TABSCHEMA
 ,        TAB.TABNAME

Colunas

  • schema_name - nome do esquema
  • table_name - nome da tabela
  • pk_name - nome da restrição de chave primária
  • colunas - lista de colunas PK separadas por ','

Linhas

  • Uma linha representa uma tabela em um banco de dados
  • Escopo das linhas: todas as tabelas em um banco de dados
  • Ordenado por esquema, nome da tabela

Columns

  • schema_name - schema name
  • table_name - table name
  • pk_name - primary key constraint name
  • columns - list of PK columns separated with ','

Rows

  • One row represents one table in a database
  • Scope of rows: all tables in a database
  • Ordered by schema, table name

Resultado - Sample results

Você pode ver quais são os nomes das restrições de PK para cada tabela e quais tabelas não têm PKs (no banco de dados SAMPLE).
You can see what are the names of PK constraints for each table and which tables don't have PKs at all (in SAMPLE database).


Copyright © Dataedo.