如何检查列是否已存在oracle

时间:2019-01-25 16:24:10

标签: sql oracle

我需要检查colum是否已经存在。我认为查询必须是这样的:

select 

..
case
          when exists ( select * from Students s where colum_name='pec')
         then nvl(SUBSTR(s.student_name , 0, 100),'') 
         else null
       end as STUDENT NAME,

但是此查询不起作用。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用USER_TAB_COLUMNS

select *  from user_tab_columns where table_name = 'MYTABLE' and COLUMN_NAME = 'COL1'

答案 1 :(得分:0)

是的,您可以进行验证。 考虑以下示例:

create table tab1( pec int, student_name varchar2(50));
insert into tab1(student_name) values('Doflamingo19');

create table tab2( pex int, student_name varchar2(50));
insert into tab2(student_name) values('Doflamingo19');

select substr(student_name ,0, 10) as student_name, 'Exists in TAB1' as Existance
  from tab1
 where exists ( select 1 
                  from user_tab_columns
                 where table_name = 'TAB1'
                   and column_name = 'PEC' )
 union all                  
 select substr(student_name ,0, 10) as student_name, 'NOT Exists in TAB2'
   from tab2
  where not 
        exists ( select 1 
                   from user_tab_columns
                 where table_name = 'TAB2'
                   and column_name = 'PEC' );

STUDENT_NAME    EXISTANCE
------------    ------------------
Doflamingo      Exists in TAB1
Doflamingo      NOT Exists in TAB2