在编写程序时,数据库结构会经常变化,所以经常需要编写一些数据库脚本,编写完成后需发往现场执行,如果已经存在或者重复执行,有些脚本会报错,所以需要判断其是否存在,现在我就把经常用到的一些判断方法和大家分享下:
一。判断oracle表是否存在的方法
declare tableexistedcount number; --声明变量存储要查询的表是否存在
begin
select count(1) into tableexistedcount from user_tables t where t.table_name = upper('test'); --从系统表中查询当表是否存在
if tableexistedcount = 0 then --如果不存在,使用快速执行语句创建新表
execute immediate
'create table test --创建测试表
(id number not null,name = varchar2(20) not null)';
end if;
end;
二。判断oracle表中的列是否存在的方法
declare columnexistedcount number; --声明变量存储要查询的表中的列是否存在
begin
--从系统表中查询表中的列是否存在
select count(1) into columnexistedcount from user_tab_columns t where t.table_name = upper('test') and t.column_name = upper('age');
--如果不存在,使用快速执行语句添加age列
if columnexistedcount = 0 then
execute immediate
'alter table test add age number not null';
end if;
end;
declare
num number;
begin
select count(1)
into num
from cols
where table_name = upper('tablename')
and column_name = upper('columnname');
if num > 0 then
execute immediate 'alter table tablename drop column columnname';
end if;
end;
三。判断oracle表是否存在主键的方法
declare primarykeyexistedcount number; --声明变量存储要查询的表中的列是否存在
begin
--从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)
select count(1) into primarykeyexistedcount from user_constraints t where t.table_name = upper('test') and t.constraint_type = 'p';
--如果不存在,使用快速执行语句添加主键约束
if primarykeyexistedcount = 0 then
execute immediate
'alter table test add constraint pk_test_id primary key(id)';
end if;
end;
四。判断oracle表是否存在外键的方法
declare foreignkeyexistedcount number; --声明变量存储要查询的表中的列是否存在
begin
--从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)
select count(1) into foreignkeyexistedcount from user_constraints t where t.table_name = upper('test') and t.constraint_type = 'r' and t.constraint_name = '外键约束名称';
--如果不存在,使用快速执行语句添加主键约束
if foreignkeyexistedcount = 0 then
execute immediate
'alter table test add constraint 外键约束名称 foreign key references 外键引用表(列)';
end if;
end;
总结
以上所述是www.887551.com给大家介绍的oracle判断表、列、主键是否存在的方法,希望对大家有所帮助