Oracle判断表、列、主键是否存在的方法
编程学习 2021-07-05 16:09www.dzhlxh.cn编程入门
这篇文章主要介绍了Oracle判断表、列、主键是否存在的方法,狼蚁网站SEO优化是长沙网络推广之家长沙网络推广给大家带来的一些判断方法和大家分享下
在编写程序时,数据库结构会经常变化,所以经常需要编写一些数据库脚本,编写完成后需发往现场执行,如果已经存在或者重复执行,有些脚本会报错,所以需要判断其是否存在,现在我就把经常用到的一些判断方法和大家分享下:
一。判断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;
总结
以上所述是长沙网络推广给大家介绍的Oracle判断表、列、主键是否存在的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!
编程语言
- Win10 PC创意者更新慢速版15048改进内容与已知问题
- 用纯CSS3实现网页中常见的小箭头
- 神舟笔记本问题集锦
- Bellnames常用操作说明
- 揭秘手机淘宝搜索排序的影响因素
- XHTML入门学习教程-网页Head和DTD
- 笔记本光驱保养常用知识
- hzhost虚拟主机系统致命漏洞
- 电脑无线网络出现红色叉叉无线网卡打不开的六
- 16项评比不得不看 机箱哪些功能最实用
- AI怎么绘制一个呲牙的qq表情-
- 红帽指点杆机械键盘 TEX Yoda上手体验测评
- 笔记本电脑保养常识有哪些-笔记本保养常识总结
- cdr怎么设计圆角矩形效果的图标-
- 在XSLT样式表中声明命名空间小结
- Fireworks教程-常用操作技巧总结