oracle中创建表时先判断是否存在表再drop的SQL
2008-06-30 17:01
459 查看
在写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了,我就犯过这样的错误。
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了,我就犯过这样的错误。
相关文章推荐
- oracle中创建表时先判断是否存在表再drop的SQL
- sql判断临时表是否存在和创建临时表的方法
- MS SQL Server中数据表、视图、函数/方法、存储过程是否存在判断及创建
- MS SQL Server中数据表、视图、函数/方法、存储过程是否存在判断及创建
- ORACLE—003:Create之创建表前判断表是否存在
- oracle创建表之前判断表是否存在,如果存在则删除已有表
- 【oracle】创建表前判断表是否存在
- oracle创建表之前判断表是否存在,如果存在则删除已有表
- Oracle之 在创建Table之前先判断是否存在,存在就删除
- SQL:判断某些元素是否存在及创建的SQL语句
- SQL语句大全:侧重创建、判断对象是否存在相关语句
- oracle创建表之前判断表是否存在,如果存在则删除已有表
- MS SQL Server中数据表、视图、函数/方法、存储过程是否存在判断及创建
- oracle创建表之前判断表是否存在,如果存在则删除已有表
- Oracle 创建表,并且判断表是否存在
- MS SQL 中判断 数据库, 存储过程,表,临时表,视图,函数,用户,用户创建对象 等是否存在 SQL脚本
- oracle创建表之前判断表是否存在,如果存在则删除已有表
- oracle创建表之前判断表是否存在,如果存在则删除已有表
- ORACLE中判断表或视图是否存在,如果不存在再创建的方法
- oracle(PL/SQL)表操作:创建表时检查数据库是否存在该表,若存在删除再创建