oracle中建立表時先判斷是否存在表再drop的SQL

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.