国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > Oracle > 正文

Oracle判斷表、列、主鍵是否存在的方法

2024-08-29 14:01:02
字體:
來源:轉載
供稿:網友

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

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

declare tableExistedCount number;  --聲明變量存儲要查詢的表是否存在begin   select 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;

三。判斷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判斷表、列、主鍵是否存在的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!


注:相關教程知識閱讀請移步到oracle教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 景东| 莱芜市| 益阳市| 千阳县| 霍州市| 石台县| 仪征市| 曲麻莱县| 新兴县| 临汾市| 沈丘县| 溧阳市| 莎车县| 天峨县| 东兰县| 长寿区| 五大连池市| 青州市| 绥芬河市| 呼伦贝尔市| 古丈县| 博野县| 大竹县| 大安市| 海淀区| 长兴县| 平武县| 嘉义市| 淳安县| 华安县| 张家口市| 大悟县| 平果县| 新邵县| 新沂市| 普兰县| 连城县| 泰来县| 荣成市| 安达市| 桃江县|