Oracle如何判断表、列、主键是否存在

32次阅读
没有评论

共计 2017 个字符,预计需要花费 6 分钟才能阅读完成。

自动写代码机器人,免费开通

这篇文章主要介绍 Oracle 如何判断表、列、主键是否存在,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

在编写程序时,数据库结构会经常变化,所以经常需要编写一些数据库脚本,编写完成后需发往现场执行,如果已经存在或者重复执行,有些脚本会报错,所以需要判断其是否存在,现在我就把经常用到的一些判断方法和大家分享下:

一。判断 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;
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;

以上是“Oracle 如何判断表、列、主键是否存在”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注丸趣 TV 行业资讯频道!

向 AI 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计2017字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)