简体   繁体   中英

Shared columns between two tables in DB2

My question is duplicate of this SO question but I want to do it for DB2 database while other question was asked for SQL Server .

I have two tables TABLE1 and TABLE2 in Schema BP . I wish to find names of columns shared between these two tables.

There are many schema on DB Server,

I don't see any generic answers there which would be applicable for all types of DBs.

A DB2 DBA at my office told me this and its giving me correct results,

SELECT BP.BP_COL FROM
(SELECT COLNAME AS BP_COL FROM SYSCAT.COLUMNS WHERE TABNAME='TABLE1' AND TABSCHEMA='BP' ) BP1
INNER JOIN
(SELECT COLNAME AS AR_COL FROM SYSCAT.COLUMNS WHERE TABNAME='TABLE2' AND TABSCHEMA='BP' ) BP2
ON BP1.BP_COL=BP2.AR_COL
WITH UR;

I'm not sure why @SabirKhan answer has so many sub-queries -- just join the meta information to itself -- an inner join will ensure you get results from both tables.

SELECT A.COLNAME AS DUP 
FROM SYSCAT.COLUMNS A 
JOIN SYSCAT.COLUMNS B ON A.COLNAME = B.COLNAME AND  B.TABNAME='TABLE2' AND B.TABSCHEMA='BP' 
WHERE A.TABNAME='TABLE1' AND A.TABSCHEMA='BP' 

As for you not seeing answers that work with all database platforms. You are correct -- there are no such answers -- database platforms vary a lot.

FWiW: For more than just the effective INTERSECT of the names, the following shows that as well as the unmatched names betwixt; the specification of the qualified SYSCOLUMNS or similar catalog VIEW and the corresponding column names may be specific to the DB2 variant such that adjustments are likely required, but the following was successful, exactly as shown, using the IBM DB2 for i 7.1 SQL:

Setup:

 create table bp.TABLE1 (in_both char, common char, only_in_t1 char )
 ;
 create table bp.TABLE2 ( only_in_t2 char, in_both char, common char)
 ;

Query of the columns:

 SELECT t1_col, t2_col                                              
 from ( select char(   column_name, 25) as t1_col                   
        from syscolumns                                             
        where    table_name = 'TABLE1' and    table_schema='BP' ) as t1
 full outer join                                                    
      ( select char(   column_name, 25) as t2_col                   
        from syscolumns                                             
        where    table_name = 'TABLE2' and    table_schema='BP' ) as t2
   on t1_col = t2_col                                               
 ; -- report from above query, with headings, follows [where a dash indicates NULL value]:
 T1_COL                     T2_COL    
 IN_BOTH                    IN_BOTH   
 COMMON                     COMMON    
 ONLY_IN_T1                 -         
 -                          ONLY_IN_T2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM