tags:

views:

31

answers:

2

I am trying to identify table types based on the columns they contain in a stored procedure. The query I initialy came up with is as follows:


SELECT CASE WHEN col_one. IS NOT NULL THEN 'COL1'
                    WHEN col_two IS NOT NULL THEN 'COL2'
               ELSE 'NEITHER'
               END
        INTO ls_table_type
        FROM (SELECT column_name col_one
          FROM sys.all_tab_cols
          WHERE upper ( owner ) = upper ( '|OWNER|' )
            AND hidden_column = 'NO'
            AND virtual_column = 'NO'
            AND column_id IS NOT NULL
            AND column_name = '|COL1_NAME|'
            AND table_name = upper(|TABLE_NAME|))
          ,(SELECT column_name as col_two
          FROM sys.all_tab_cols
          WHERE upper ( owner ) = upper ( '|OWNER|' )
            AND hidden_column = 'NO'
            AND virtual_column = 'NO'
            AND column_id IS NOT NULL
            AND column_name = '|COL2_NAME|'
            AND table_name = upper(|TABLE_NAME|))

This does not work unless both columns are present in a table. I am sure I am missing some obvious way of attacking this.

A: 

This query should give you the information you need. If col1 and col2 don't exist in the same table then you won't get any duplicate records.

select table_name, column_name
from all_tab_cols
where owner = '?'
  and column_name in ('col1', 'col2')
  and table_name = '?'; -- this line optional
ar
A: 

You could try this:

SELECT CASE WHEN EXISTS (SELECT column_name col_one
      FROM sys.all_tab_cols
      WHERE upper ( owner ) = upper ( '|OWNER|' )
        AND hidden_column = 'NO'
        AND virtual_column = 'NO'
        AND column_id IS NOT NULL
        AND column_name = '|COL1_NAME|'
        AND table_name = upper('|TABLE_NAME|'))
    THEN 'COL1'
    WHEN EXISTS (SELECT column_name as col_two
      FROM sys.all_tab_cols
      WHERE upper ( owner ) = upper ( '|OWNER|' )
        AND hidden_column = 'NO'
        AND virtual_column = 'NO'
        AND column_id IS NOT NULL
        AND column_name = '|COL2_NAME|'
        AND table_name = upper('|TABLE_NAME|'))
    THEN 'COL2'
    ELSE 'NEITHER'
    END
FROM DUAL;        
Tony Andrews