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

判断表是否存在

declare 
    n_count number;   --声明变量存储要查询的表是否存在  
begin   
     select count(1) into n_count  from user_tables t where t.table_name = upper('表名'); --从系统表中查询当表是否存在  
     if n_count  = 0 then --如果不存在,使用快速执行语句创建新表  
         execute immediate  
         'create table 表名 --创建测试表  
         (ID number not null,Name = varchar2(20) not null)';  
     end if;  
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 = 0 then   
           execute immediate  
           'alter table 表名 add 列名 number not null';  
        end if;  
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  = 0 then   
        execute immediate  
        'alter table 表名 add constraint PK_表名_ID primary key(id)';  
        end if;  
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 = 0 then   
           execute immediate  
           'alter table 表名 add constraint 外键约束名称 foreign key references 外键引用表(列)';  
        end if;  
end;  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值