在寫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了,我就犯過這樣的錯誤。