Oracle判断表、列、主键是否存在的方法
在编写程序时Oracle判断表、列、主键是否存在的方法,数据库结构会经常变化,所以经常需要编写一些数据库脚本oracle 忽略重复主键,编写完成后需发往现场执行Oracle判断表、列、主键是否存在的方法,如果已经存在或者重复执行,有些脚本会报错,所以需要判断其是否存在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;

二。判断表中的列是否存在的方法
declare columnExistedCount number; --声明变量存储要查询的表中的列是否存在
begin
--从系统表中查询表中的列是否存在
select count() into columnExistedCount from user_tab_columns t where t.table_name = upper('Test') and t.column_name = upper('Age');
--如果不存在,使用快速执行语句添加Age列
if columnExistedCount = then
execute immediate
'alter table Test add age number not null';
end if;
end;
DECLARE
num NUMBER;
BEGIN
SELECT COUNT()
INTO num
from cols
where table_name = upper('tableName')
and column_name = upper('columnName');
IF num > THEN
execute immediate 'alter table tableName drop column columnName';
END IF;
END;
三。判断表是否存在主键的方法
declare primaryKeyExistedCount number; --声明变量存储要查询的表中的列是否存在
begin
--从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)
select count() into primaryKeyExistedCount from user_constraints t where t.table_name = upper('Test') and t.constraint_type = 'P';
--如果不存在,使用快速执行语句添加主键约束
if primaryKeyExistedCount = then
execute immediate
'alter table Test add constraint PK_Test_ID primary key(id)';
end if;
end;

四。判断表是否存在外键的方法
declare foreignKeyExistedCount number; --声明变量存储要查询的表中的列是否存在
begin
--从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)
select count() into foreignKeyExistedCount from user_constraints t where t.table_name = upper('Test') and t.constraint_type = 'R' and t.constraint_name = '外键约束名称';
--如果不存在,使用快速执行语句添加主键约束
if foreignKeyExistedCount = then
execute immediate
'alter table Test add constraint 外键约束名称 foreign key references 外键引用表(列)';
end if;
end;
公告:
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299
资源库 - 资源分享下载网 » Oracle判断表、列、主键是否存在的方法
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299
资源库 - 资源分享下载网 » Oracle判断表、列、主键是否存在的方法
常见问题FAQ
- 关于资源售价和售后服务的说明?
- 代码有没有售后服务和技术支持?
- 有没有搭建服务?
- 链接地址失效了怎么办?
- 关于解压密码

