久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

Oracle如何判斷表、列、主鍵是否存在

137次閱讀
沒有評論

共計 2017 個字符,預計需要花費 6 分鐘才能閱讀完成。

自動寫代碼機器人,免費開通

這篇文章主要介紹 Oracle 如何判斷表、列、主鍵是否存在,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

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

一。判斷 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;
DECLARE
num NUMBER;
BEGIN
SELECT COUNT(1)
INTO num
from cols
where table_name = upper(tableName)
and column_name = upper( columnName 
IF num   0 THEN
execute 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 如何判斷表、列、主鍵是否存在”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注丸趣 TV 行業資訊頻道!

向 AI 問一下細節

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-12-04發表,共計2017字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 威远县| 巴彦淖尔市| 沈阳市| 文昌市| 平谷区| 民权县| 来宾市| 海阳市| 瓦房店市| 嘉荫县| 广元市| 松阳县| 邻水| 庆安县| 龙陵县| 江山市| 恩平市| 鄂伦春自治旗| 武功县| 调兵山市| 宜都市| 文昌市| 临邑县| 象州县| 光山县| 徐闻县| 竹山县| 普陀区| 浙江省| 泸水县| 宜良县| 稻城县| 黄冈市| 大石桥市| 怀安县| 开远市| 余姚市| 定西市| 武冈市| 峨山| 揭西县|