oracle中创建表时先判断是否存在表再drop的SQL

来源:互联网 发布:大学要考的证书 知乎 编辑:程序博客网 时间:2024/06/06 09:38

    在写oracle的创建表的SQL时,为了SQL能够反复执行,一般都会在create前面加入drop表的语句,但这样先drop再create的语句在第一次执行时,会报一个不存在该表的错误,查了一下,oracle中没有像sybase那样先判断是否存在表再drop表的语句。

    sybase中用以下语句就能轻松判断是否已经存在了某表:

if exists (select 1             from  sysobjects             where  id = object_id('user_info')             and    type = 'U')    drop table user_info go

或者

if object_id('xxx_view')is not null    drop view xxx_view go

    第一种方式中其中type为对象的类型,如果对象是view,刚type='V'

     而oracle中,并没有这样方便的语句,然而我们难道就不能实现这个功能了吗?

     可以利用存储过程来实现,例如以下语句:

declare num number; begin select count(1) into num from user_tables where table_name='user_info'; if num>0 then execute immediate 'drop table user_info'; end if; execute immediate 'create table user_info (user_code varchar2(10) not null,  user_name varchar2(30), sex    varchar2(1), constraint pk_user_info primary key (user_code))'; end; /

    不过将这样的存储过程与正常的sql放在一起执行时,一定要加最后一行的“/”,以告诉编译器存储过程执行完毕,可以继续执行正常的SQL了,我就犯过这样的错误。

原创粉丝点击