转:Oracle判断表、列、主键是否存在的方法

转载地址:http://blog.csdn.net/wxdzxl/article/details/8063774

一。判断Oracle表是否存在的方法

  1. declare tableExistedCount number;   --声明变量存储要查询的表是否存在  
  2. begin   
  3.      select count(1) into tableExistedCount  from user_tables t where t.table_name = upper('Test'); --从系统表中查询当表是否存在  
  4.      if tableExistedCount  = 0 then --如果不存在,使用快速执行语句创建新表  
  5.          execute immediate  
  6.          'create table Test --创建测试表  
  7.          (ID number not null,Name = varchar2(20) not null)';  
  8.      end if;  
  9. end;  

二。判断Oracle表中的列是否存在的方法

  1. declare columnExistedCount number;   --声明变量存储要查询的表中的列是否存在  
  2. begin   
  3.         --从系统表中查询表中的列是否存在  
  4.         select count(1) into columnExistedCount from user_tab_columns t where t.table_name = upper('Test')  and t.column_name = upper('Age');       
  5.         --如果不存在,使用快速执行语句添加Age列  
  6.         if columnExistedCount = 0 then   
  7.            execute immediate  
  8.            'alter table Test add age number not null';  
  9.         end if;  
  10. end;  

三。判断Oracle表是否存在主键的方法

  1. declare primaryKeyExistedCount number;   --声明变量存储要查询的表中的列是否存在  
  2. begin   
  3.         --从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)  
  4.         select count(1) into primaryKeyExistedCount from user_constraints t where t.table_name = upper('Test'and t.constraint_type = 'P';       
  5.         --如果不存在,使用快速执行语句添加主键约束  
  6.         if primaryKeyExistedCount  = 0 then   
  7.         execute immediate  
  8.         'alter table Test add constraint PK_Test_ID primary key(id)';  
  9.         end if;  
  10. end;  

四。判断Oracle表是否存在外键的方法

  1. declare foreignKeyExistedCount number;   --声明变量存储要查询的表中的列是否存在  
  2. begin   
  3.         --从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)  
  4.         select count(1) into foreignKeyExistedCount from user_constraints t where t.table_name = upper('Test'and t.constraint_type = 'R' and t.constraint_name = '外键约束名称';       
  5.         --如果不存在,使用快速执行语句添加主键约束  
  6.         if foreignKeyExistedCount = 0 then   
  7.            execute immediate  
  8.            'alter table Test add constraint 外键约束名称 foreign key references 外键引用表(列)';  
  9.         end if;  
  10. end

猜你喜欢

转载自huiy.iteye.com/blog/2246650