应用场合:数据表新增自增一主键能加快数据表的访问速度,而且是整形的索引速度最快。本程序适合在导入Oracle数据库时删除不存在主键的情况下运行。

代码说明:所有的表主键字段名都设置为ID,如果已存在ID字段,则判断是否是整形,如果不是就重命名字段为[表名ID],然后新增ID,如果不存在则直接添加自增一ID的主键

操作说明:打开PQSQL连接数据库后直接执行下面的详细脚本代码运行即可,脚本有风险(会删除原来的索引跟主键约束),请不要轻易在正式运行的数据库上直接执行

--Oracle使用游标为所有用户表添加主键语句
--参考语句如下:
--查询所有主键约束select * from user_constraints
--查询所有序列select * from user_sequences;
--查询所有触发器select * from user_triggers;
--查询触发器的用户select distinct(table_owner) from user_triggers;

declare

addstring NVARCHAR2(2000):=' '; --定义添加字段变量 
renamestring NVARCHAR2(2000):=' '; --定义重命名字段变量 
tablestring NVARCHAR2(2000):=' '; --定义序列变量
keyidname NVARCHAR2(255):='ID'; --定义主键字段名变量
tableidname NVARCHAR2(255):=' '; --定义新的字段名变量
trigerstring NVARCHAR2(2000):=' '; --定义创建触发器字符串变量    
trgname NVARCHAR2(255):=' '; --定义触发器名称变量 
seqstring NVARCHAR2(2000):=' '; --定义创建序列字符串变量   
seqname NVARCHAR2(255):=' '; --定义序列名称变量
pkname NVARCHAR2(255):=' '; --定义主键索引名称变量

constring NVARCHAR2(2000):=' '; --定义索引变量  
notnullstring NVARCHAR2(2000):=' '; --定义主键不为空变量

cursor mycursor is select * from user_tables where TABLESPACE_NAME='SZGABL' ORDER BY TABLE_NAME; --定义游标获取所所有用户数据表名称
myrecord mycursor%rowtype;  --定义游标记录类型
CounterName int :=0;   --定义是否存在对应的列名变量
CounterData int :=0;   --定义是否存在对应的数据类型

begin

dbms_output.put_line('declare counter int :=0;begin ');

open mycursor;  --打开游标  
if mycursor%isopen  then  --判断打开成功  
loop --循环获取记录集    
fetch mycursor into myrecord; --获取游标中的记录

if mycursor%found then  --游标的found属性判断是否有记录 
begin
  --获取有效的数据表名
  select replace(myrecord.TABLE_NAME,'TB_','') into tablestring from dual;
  select 'SEQ_'||tablestring into seqname from dual;
  select 'TRG_'||tablestring into trgname from dual;
  select 'PK_'||tablestring into pkname from dual; 
  select tablestring||UPPER(keyidname) into tableidname from dual;
 
  --判断当前数据表是否包含字段名为ID的列
  SELECT COUNT(*) INTO CounterName FROM dual WHERE EXISTS(SELECT * FROM user_tab_cols WHERE LOWER(COLUMN_NAME)=LOWER(keyidname) and TABLE_NAME=myrecord.TABLE_NAME);
  if CounterName=0 then
    begin
     dbms_output.put_line('--当前数据表'||myrecord.TABLE_NAME||'不存在字段名为ID的列');
         --添加主键字段
         addstring:='execute immediate ''alter table '||myrecord.TABLE_NAME||' add '||keyidname||' NUMBER'';';
         dbms_output.put_line(addstring);
         --execute immediate addstring;

--创建一个序列        
         seqstring:='select count(*) into counter from dual  where exists(select * from user_sequences where sequence_name='''||seqname||''');if counter>0 then execute immediate ''drop sequence '||seqname||'''; end if; execute immediate '' create sequence SEQ_'||tablestring||'  INCREMENT BY 1 START WITH 1  NOMAXVALUE  NOCYCLE  NOCACHE'';';      
         dbms_output.put_line(seqstring);
         --execute immediate seqstring;
         --创建一个触发器
         trigerstring:='select count(*) into counter from dual  where exists(select * from user_triggers where trigger_name='''||trgname||''');if counter>0 then execute immediate ''drop trigger '||trgname||'''; end if; execute immediate '' create trigger TRG_'||tablestring||' BEFORE INSERT ON '||myrecord.TABLE_NAME||' FOR EACH ROW WHEN (new.'||keyidname||' is null) begin  select '||seqname||'.nextval into: new.'||keyidname||' from dual; end'';';          
         dbms_output.put_line(trigerstring);
         --execute immediate trigerstring;
         --添加主键约束
         constring:='select count(*) into counter from dual  where exists(select * from user_constraints where constraint_name='''||pkname||''');if counter>0 then execute immediate ''drop constraint '||pkname||'''; end if; execute immediate ''alter table '||myrecord.TABLE_NAME||' add constraint '||pkname||' primary key('||keyidname||')'';';
         dbms_output.put_line(constring);
         --execute immediate constring;
         --更新主键不为空
         notnullstring:='select count(*) into counter from dual  where exists(select * from user_tab_cols where table_name='''||myrecord.TABLE_NAME||'''  and column_name='''||keyidname||''' AND NULLABLE=''Y'' );if counter>0 then execute immediate ''alter table '||myrecord.TABLE_NAME||' modify '||keyidname||' not null''; end if;';
         dbms_output.put_line(notnullstring);
         --execute immediate notnullstring;
     end;
  else    
    begin
      --判断当前数据表是否包含字段名为ID且数据类型为NUMBER
      SELECT COUNT(*) INTO CounterData FROM dual WHERE EXISTS(SELECT * FROM user_tab_cols WHERE LOWER(COLUMN_NAME)=LOWER(keyidname) AND DATA_TYPE='NUMBER' and TABLE_NAME=myrecord.TABLE_NAME);
      if CounterData=0 then   
         begin
         dbms_output.put_line('--当前数据表'||myrecord.TABLE_NAME||'存在字段名为ID,但数据类型不为NUMBER的列');
         --先重命名字段,然后添加主键字段        
         renamestring:='execute immediate ''alter table '||myrecord.TABLE_NAME||' rename column '||keyidname||' to '||tableidname||''';';
         dbms_output.put_line(renamestring);
         --execute immediate renamestring;
         --添加主键字段         
         addstring:='execute immediate ''alter table '||myrecord.TABLE_NAME||' add '||keyidname||' NUMBER'';';
         dbms_output.put_line(addstring);

--execute immediate addstring;      
         --创建一个序列   
         seqstring:='select count(*) into counter from dual  where exists(select * from user_sequences where sequence_name='''||seqname||''');if counter>0 then execute immediate ''drop sequence '||seqname||'''; end if; execute immediate '' create sequence SEQ_'||tablestring||'  INCREMENT BY 1 START WITH 1  NOMAXVALUE  NOCYCLE  NOCACHE'';';
         dbms_output.put_line(seqstring);
         --execute immediate seqstring;
         --创建一个触发器
         trigerstring:='select count(*) into counter from dual  where exists(select * from user_triggers where trigger_name='''||trgname||''');if counter>0 then execute immediate ''drop trigger '||trgname||'''; end if; execute immediate '' create trigger TRG_'||tablestring||' BEFORE INSERT ON '||myrecord.TABLE_NAME||' FOR EACH ROW WHEN (new.'||keyidname||' is null) begin  select '||seqname||'.nextval into: new.'||keyidname||' from dual; end'';';          
         dbms_output.put_line(trigerstring);
         --execute immediate trigerstring;
         --添加主键约束
         constring:='select count(*) into counter from dual  where exists(select * from user_constraints where constraint_name='''||pkname||''');if counter>0 then execute immediate ''drop constraint '||pkname||'''; end if; execute immediate ''alter table '||myrecord.TABLE_NAME||' add constraint '||pkname||' primary key('||keyidname||')'';';
         dbms_output.put_line(constring);
         --execute immediate constring;  
         --更新主键不为空        
         notnullstring:='select count(*) into counter from dual  where exists(select * from user_tab_cols where table_name='''||myrecord.TABLE_NAME||'''  and column_name='''||keyidname||''' AND NULLABLE=''Y'' );if counter>0 then execute immediate ''alter table '||myrecord.TABLE_NAME||'  modify '||keyidname||' not null''; end if;';
         dbms_output.put_line(notnullstring);
         --execute immediate notnullstring;           
         end;
      else
        begin
         dbms_output.put_line('--当前数据表'||myrecord.TABLE_NAME||'存在字段名为ID,且数据类型为NUMBER的列');    
         --创建一个序列   
         seqstring:='select count(*) into counter from dual  where exists(select * from user_sequences where sequence_name='''||seqname||''');if counter>0 then execute immediate ''drop sequence '||seqname||'''; end if; execute immediate '' create sequence SEQ_'||tablestring||'  INCREMENT BY 1 START WITH 1  NOMAXVALUE  NOCYCLE  NOCACHE'';';  
         dbms_output.put_line(seqstring);
         --execute immediate seqstring;
         --创建一个触发器
         trigerstring:='select count(*) into counter from dual  where exists(select * from user_triggers where trigger_name='''||trgname||''');if counter>0 then execute immediate ''drop trigger '||trgname||'''; end if; execute immediate '' create trigger TRG_'||tablestring||' BEFORE INSERT ON '||myrecord.TABLE_NAME||' FOR EACH ROW WHEN (new.'||keyidname||' is null) begin  select '||seqname||'.nextval into: new.'||keyidname||' from dual; end'';';          
         dbms_output.put_line(trigerstring);
         --execute immediate trigerstring;
         --添加主键约束        
         constring:='select count(*) into counter from dual  where exists(select * from user_constraints where constraint_name='''||pkname||''');if counter>0 then execute immediate ''drop constraint '||pkname||'''; end if; execute immediate ''alter table '||myrecord.TABLE_NAME||' add constraint '||pkname||' primary key('||keyidname||')'';';
         dbms_output.put_line(constring);
         --execute immediate constring;
         --更新主键不为空
         notnullstring:='select count(*) into counter from dual  where exists(select * from user_tab_cols where table_name='''||myrecord.TABLE_NAME||'''  and column_name='''||keyidname||''' AND NULLABLE=''Y'' );if counter>0 then execute immediate ''alter table '||myrecord.TABLE_NAME||'  modify '||keyidname||' not null''; end if;';
         dbms_output.put_line(notnullstring);
         --execute immediate notnullstring;    
         end;
      end if;
    end;
  end if;
      dbms_output.put_line('');
end;

else
exit;
end if;
  
end loop;  
else    
dbms_output.put_line('--游标没有打开');  
end if;

close mycursor;

dbms_output.put_line('end;');
end;

Oracle使用游标为所有用户表添加主键语句的更多相关文章

  1. Oracle表添加主键、外键

    1.创建表的同时创建主键约束 (1)无命名 create table student ( studentid int primary key not null, studentname varchar ...

  2. SQL Server 创建表 添加主键 添加列常用SQL语句

    --删除主键 alter table 表名 drop constraint 主键名 --添加主键 alter table 表名 add constraint 主键名 primary key(字段名1, ...

  3. 创建表 添加主键 添加列常用SQL语句

    --删除主键 alter table 表名 drop constraint 主键名--添加主键alter table 表名 add constraint 主键名 primary key(字段名1,字段 ...

  4. SQL Server 创建表 添加主键 添加列常用SQL语句【转】

    --删除主键alter table 表名 drop constraint 主键名--添加主键alter table 表名 add constraint 主键名 primary key(字段名1,字段名 ...

  5. Oracle 给表添加主键和使ID自增、触发器、创建结构一样的表

    1.关于主键:在建表时指定primary key字句即可:create table test( id number(6) primary key, name varchar2(30));如果是对于已经 ...

  6. 为 mysql 数据表添加主键

    DROP TABLE IF EXISTS `sdo_actData`.`actCDKey`; CREATE TABLE `sdo_actData`.`actCDKey` ( `RoleID` ) ' ...

  7. 为一个有数据没有主键id的数据表添加主键字段

    ALTER TABLE `photo_feedbacks` ADD COLUMN `id`  int(11) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KE ...

  8. sqlserver添加主键

    sqlServer中给表添加主键的sql: alter table market_media_medical_history alter column pk_id bigint not null; a ...

  9. SqlServer数据库优化之添加主键和自增长

    今天需要给有500万条数据的表添加主键和自增长列,其中最大的难度在于如何UPDATE这500万多条数据,开始吧! 1.先给表添加一个字段叫ID,并允许空 2.查询表,我想到了使用其中的时间列排序来创建 ...

随机推荐

  1. 微信小程序-参数传递与事件处理

    前言 开发过程中经常会遇到从一个页面携带数据到另一个页面的情况,所以需要知道以下信息,什么是事件?有哪些传递方式?如果传递数组呢?如果传递对象呢? 一.事件 什么是事件 事件是视图层到逻辑层的通讯方式 ...

  2. Unix系统的文件打开机构

    当打开一个文件时,建立用户与该文件的联系.其实质是将该文件在辅存中的有关目录信息.辅存i节点及相应的文件地址索引表拷贝到主存中.文件系统中管理这一方面的机构成为打开文件管理机构,简称打开文件机构. 打 ...

  3. React 深入系列4:组件的生命周期

    文:徐超,<React进阶之路>作者 授权发布,转载请注明作者及出处 React 深入系列4:组件的生命周期 React 深入系列,深入讲解了React中的重点概念.特性和模式等,旨在帮助 ...

  4. H3C系列之三层交换机系统版本升级

    本文涉及到的硬件与软件交换机:H3C S3600-28TP-SItftp软件:tftpd32小软件升级的文件:S36SI_E-CMW310-R1702P44.zip 关于升级的文件说明如下: S36S ...

  5. C# ref与out

    ref参数是引用,out参数为输出参数.我写一个控制台的程序来说明一下两者的特点和区别: class Program { 3 public static void RefMethod( ref int ...

  6. PHP $_POST 变量

    $_POST 变量 预定义的 $_POST 变量用于收集来自 method="post" 的表单中的值. 从带有 POST 方法的表单发送的信息,对任何人都是不可见的(不会显示在浏 ...

  7. PHP Misc. 函数

    PHP 杂项函数简介 我们把不属于其他类别的函数归纳到杂项函数类别. 安装 杂项函数是 PHP 核心的组成部分.无需安装即可使用这些函数. Runtime 配置 杂项函数的行为受 php.ini 文件 ...

  8. 安卓7.1 新特性Shortcut

    介绍 Shortcut 是谷歌在API25提出来的 类似苹果3D touch 但是没有压力感应.在安卓中完全就是长按. 来看下效果吧: 是不是很赞? 那么请随本文一起学习吧 更新 新建项目 在你项目下 ...

  9. FindBugs入门简介(eclipse安装使用实例)

    前言:一般公司都会有一些开发规范,但是事实上,简单看那么一两遍并不能养成习惯,或者将这些规范记住.特别的,对于一些新手,写的代码往往会很糟糕.回头看看你一两年前写的代码就会知道,所谓的"糟糕 ...

  10. MYSQL 更新时间自动同步与创建时间默认值共存问题

    本文作者:苏生米沿 本文地址:http://blog.csdn.net/sushengmiyan/article/details/50326259 在使用SQL的时候,希望在更新数据的时候自动填充更新 ...