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

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

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

declaretableExistedCountnumber;--声明变量存储要查询的表是否存在beginselectcount(1)intotableExistedCountfromuser_tablestwheret.table_name=upper('Test');--从系统表中查询当表是否存在iftableExistedCount=0then--如果不存在,使用快速执行语句创建新表executeimmediate'createtableTest--创建测试表(IDnumbernotnull,Name=varchar2(20)notnull)';endif;end;

二。判断Oracle表中的列是否存在的方法

declarecolumnExistedCountnumber;--声明变量存储要查询的表中的列是否存在begin--从系统表中查询表中的列是否存在selectcount(1)intocolumnExistedCountfromuser_tab_columnstwheret.table_name=upper('Test')andt.column_name=upper('Age');--如果不存在,使用快速执行语句添加Age列ifcolumnExistedCount=0thenexecuteimmediate'altertableTestaddagenumbernotnull';endif;end;DECLAREnumNUMBER;BEGINSELECTCOUNT(1)INTOnumfromcolswheretable_name=upper('tableName')andcolumn_name=upper('columnName');IFnum>0THENexecuteimmediate'altertabletableNamedropcolumncolumnName';ENDIF;END;

三。判断Oracle表是否存在主键的方法

declareprimaryKeyExistedCountnumber;--声明变量存储要查询的表中的列是否存在begin--从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)selectcount(1)intoprimaryKeyExistedCountfromuser_constraintstwheret.table_name=upper('Test')andt.constraint_type='P';--如果不存在,使用快速执行语句添加主键约束ifprimaryKeyExistedCount=0thenexecuteimmediate'altertableTestaddconstraintPK_Test_IDprimarykey(id)';endif;end;

四。判断Oracle表是否存在外键的方法

declareforeignKeyExistedCountnumber;--声明变量存储要查询的表中的列是否存在begin--从系统表中查询表是否存在主键(因一个表只可能有一个主键,所以只需判断约束类型即可)selectcount(1)intoforeignKeyExistedCountfromuser_constraintstwheret.table_name=upper('Test')andt.constraint_type='R'andt.constraint_name='外键约束名称';--如果不存在,使用快速执行语句添加主键约束ifforeignKeyExistedCount=0thenexecuteimmediate'altertableTestaddconstraint外键约束名称foreignkeyreferences外键引用表(列)';endif;end;

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