Oracle判断表、列、主键是否存在的方法
数据库  /  管理员 发布于 6年前   448
在编写程序时,数据库结构会经常变化,所以经常需要编写一些数据库脚本,编写完成后需发往现场执行,如果已经存在或者重复执行,有些脚本会报错,所以需要判断其是否存在,现在我就把经常用到的一些判断方法和大家分享下:
一。判断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;DECLAREnum NUMBER;BEGINSELECT COUNT(1)INTO numfrom colswhere table_name = upper('tableName')and column_name = upper('columnName');IF num > 0 THENexecute 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判断表、列、主键是否存在的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号