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

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

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

1
2
3
4
5
6
7
8
9
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;
复制代码

 

posted @   特务小强  阅读(8122)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
历史上的今天:
2012-04-24 输入一个整数数组,调整数组中数字的顺序,使得所有的奇数位于数组的前半部分。
2011-04-24 ASP.NET中进行消息处理(MSMQ)
点击右上角即可分享
微信分享提示