Oracle 判斷列 表 主鍵是否存在

2021-09-11 03:06:13 字數 1887 閱讀 7295

declare 

n_count number;

--宣告變數儲存要查詢的表是否存在

begin

select

count(1

)into n_count from user_tables t where t.table_name = upper(

'表名');

--從系統表中查詢當表是否存在

if n_count =

0then

--如果不存在,使用快速執行語句建立新錶

execute immediate

'create table 表名 --建立測試表

(id number not null,name = varchar2(20) not null)'

;endif;

end;

declare 

n_count number;

--宣告變數儲存要查詢的表中的列是否存在

begin

--從系統表中查詢表中的列是否存在

select

count(1

)into n_count from user_tab_columns t where t.table_name = upper(

'表名'

)and t.column_name = upper(

'列名');

--如果不存在,使用快速執行語句新增列

if n_count =

0then

execute immediate

'alter table 表名 add 列名 number not null'

;endif;

end;

declare 

n_count number;

--宣告變數儲存要查詢的表中的主鍵是否存在

begin

--從系統表中查詢表是否存在主鍵(因乙個表只可能有乙個主鍵,所以只需判斷約束型別即可)

select

count(1

)into n_count from user_constraints t where t.table_name = upper(

'表名'

)and t.constraint_type =

'p';

--如果不存在,使用快速執行語句新增主鍵約束

if n_count =

0then

execute immediate

'alter table 表名 add constraint pk_表名_id primary key(id)'

;endif;

end;

declare 

n_count number;

--宣告變數儲存要查詢的表中的外來鍵是否存在

begin

select

count(1

)into n_count from user_constraints t where t.table_name = upper(

'表名'

)and t.constraint_type =

'r'and t.constraint_name =

'外來鍵約束名稱'

;--如果不存在,使用快速執行語句新增外來鍵約束

if n_count =

0then

execute immediate

'alter table 表名 add constraint 外來鍵約束名稱 foreign key references 外來鍵引用表(列)'

;endif;

end;

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

在編寫程式時,資料庫結構會經常變化,所以經常需要編寫一些資料庫指令碼,編寫完成後需發往現場執行,如果已經存在或者重複執行,有些指令碼會報錯,所以需要判斷其是否存在,現在我就把經常用到的一些判斷方法和大家分享下 一.判斷oracle表是否存在的方法 declare tableexistedcount ...

php判斷是否是檔案 php 判斷檔案是否存在

sha1 file 計算文字檔案sha 1雜湊 sha1 file file 語法 sha1 file file,raw 引數 file 必需。規定要計算的檔案。raw 可選。布林值,規定十六進製制或二進位制輸出格式 true 原始 16 字元二進位制格式 false 預設。32 字元十六進製制數 ...

Oracle刪除表前判斷表名是否存在若存在則刪除

在oracle中若刪除乙個不存在mrzlypj的表,如 drop table notexisttable 則會提示 ora 00942 表或檢視不存在,若使用程式執行該語句則會報異常,這就需要我們再刪除表前判斷該錶是否存在,若存在則刪除.下面是不使用儲存過程實現刪除表的sql 複製 如下 decla...