日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Oracle判断表、列、主键是否存在的方法

發布時間:2024/5/14 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Oracle判断表、列、主键是否存在的方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

在編寫程序時,數據庫結構會經常變化,所以經常需要編寫一些數據庫腳本,編寫完成后需發往現場執行,如果已經存在或者重復執行,有些腳本會報錯,所以需要判斷其是否存在,現在我就把經常用到的一些判斷方法和大家分享下:

一.判斷Oracle表是否存在的方法

declare tableExistedCount number;?? --聲明變量存儲要查詢的表是否存在beginselect?count(1)?into?tableExistedCount??from?user_tables t?where?t.table_name = upper('Test'); --從系統表中查詢當表是否存在if?tableExistedCount? = 0 then --如果不存在,使用快速執行語句創建新表execute immediate'create table Test --創建測試表(ID number not?null,Name = varchar2(20) not?null)';end?if;end;

二.判斷Oracle表中的列是否存在的方法

declare columnExistedCount number; --聲明變量存儲要查詢的表中的列是否存在 begin --從系統表中查詢表中的列是否存在select count(1) into columnExistedCount from user_tab_columns t where t.table_name = upper('Test') and t.column_name = upper('Age'); --如果不存在,使用快速執行語句添加Age列if columnExistedCount = 0 then execute immediate'alter table Test add age number not null';end if; end;

?我們需要在刪除字段前先判斷該字段是否存在,若存在則刪除,否則會報錯

DECLAREnum NUMBER; BEGINSELECT COUNT(1)INTO numfrom colswhere table_name = upper('tableName')and column_name = upper('columnName');IF num > 0 THENexecute immediate 'alter table tableName drop column columnName';END IF; END;

?我們需要在添加字段前先判斷該字段是否存在,若不存在則添加,否則會報錯

DECLAREnum NUMBER; BEGINSELECT COUNT(1)INTO numfrom colswhere table_name = upper('tableName')and column_name = upper('columnName');IF num > 0 THENexecute immediate 'alter table tableName drop column columnName';END IF; END;

三.判斷Oracle表是否存在主鍵的方法

declare primaryKeyExistedCount number; --聲明變量存儲要查詢的表中的列是否存在 begin --從系統表中查詢表是否存在主鍵(因一個表只可能有一個主鍵,所以只需判斷約束類型即可)select count(1) into primaryKeyExistedCount from user_constraints t where t.table_name = upper('Test') and t.constraint_type = 'P'; --如果不存在,使用快速執行語句添加主鍵約束if primaryKeyExistedCount = 0 then execute immediate'alter table Test add constraint PK_Test_ID primary key(id)';end if; end;

四.判斷Oracle表是否存在外鍵的方法

declare foreignKeyExistedCount number; --聲明變量存儲要查詢的表中的列是否存在 begin --從系統表中查詢表是否存在主鍵(因一個表只可能有一個主鍵,所以只需判斷約束類型即可)select count(1) into foreignKeyExistedCount from user_constraints t where t.table_name = upper('Test') and t.constraint_type = 'R' and t.constraint_name = '外鍵約束名稱'; --如果不存在,使用快速執行語句添加主鍵約束if foreignKeyExistedCount = 0 then execute immediate'alter table Test add constraint 外鍵約束名稱 foreign key references 外鍵引用表(列)';end if; end;

?

總結

以上是生活随笔為你收集整理的Oracle判断表、列、主键是否存在的方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。