数据库结构操作脚本(一)

2014-11-24 09:49:37 · 作者: · 浏览: 2
/*
数据库操作脚本汇集

*/


--删除重复数据
-------------删除重复数据--------------------------
declare
pvar_i_cunt integer;
sStockcode varchar2(20);
sExchange varchar2(10);
sSql varchar2(1000);
begin
/*
删除重复数据:
用一个临时表保存重复数据,但只记录重复数据中的一条(rowid最大的一条),然后将这表来关联实际表,
把重复数据中rowid不是最大其它数据删除,这样就剩下一条了。
*/
--创建一个临时表来保存重复数据(这个表里面:只记录其中一条--rowid最大的一条)
select count(1) into pvar_i_cunt from user_tables s where s.TABLE_NAME='TMP_STOCKCOMPS';
if pvar_i_cunt>0 then
execute immediate 'drop table TMP_STOCKCOMPS';
end if ;
execute immediate ' create table TMP_STOCKCOMPS
(
row_id ROWID,
-----------下面字段是主键字段----------------
vc_stock_code VARCHAR2(20) not null,
vc_exchange VARCHAR2(20) default '' '' not null
)' ;


for cur in (select a.cn, a.vc_stock_code, vc_exchange
from (select count(*) cn, s.vc_stock_code, s.vc_exchange
from STOCKCOMPS s
group by s.vc_stock_code, s.vc_exchange) a
where a.cn > 1) loop
sStockcode := cur.vc_stock_code;
sExchange := cur.vc_exchange;

--取出重复数据的其中一条(max(rowid)那条)
sSql :=' insert into TMP_STOCKCOMPS '
||' (row_id, vc_stock_code, vc_exchange) '
||' select max(a.rowid), a.vc_stock_code, a.vc_exchange '
||' from STOCKCOMPS a '
||' where a.vc_stock_code = '''|| sStockcode||''''
||' and a.vc_exchange = '''||sExchange||''''
||' group by a.vc_stock_code, a.vc_exchange ';

execute immediate sSql ;
end loop;

--删除重复数据,用rowid来关联(重复数据中rowid不等于临时表的row_id的数据删除,这时只剩下一条)
sSql := 'delete from STOCKCOMPS s '
||' where Exists (select ''X'' from TMP_STOCKCOMPS b '
||' where b.vc_stock_code=s.vc_stock_code '--主键字段必须要
||' and b.vc_exchange = s.vc_exchange ' --主键字段必须要
||' and b.row_id <> s.rowid) '; --rowid来判断删除

execute immediate sSql ;

commit;

--操作完成后删除临时表
execute immediate 'drop table TMP_STOCKCOMPS';
end;
/

-- user_constraints 主键约束
declare
tm_i integer;
pvar_PK_constraint varchar2(100);
begin
--查出主键,并删除,重新建立
select count(*) into tm_i from user_constraints
where table_name='表名' and constraint_type='P' ;

if tm_i>0 then
select constraint_name into pvar_PK_constraint from user_constraints
where table_name='表名' and constraint_type='P' ;
--删除主键
execute immediate 'alter table 表名drop constraint '|| pvar_PK_constraint ||' cascade';
end if ;
--再检查是否有重名的索引
select count(*) into tm_i from user_indexes
where index_name='主键名称';
if tm_i>0 then
execute immediate 'DROP INDEX 主键名称';
end if;

---创建主键
execute immediate 'alter table 表名add constraint 主键名称primary key (字段1,字段2,....)';
end;


-- user_tab_cols 表增加字段
declare
tm_i integer;
Begin

--如果字段关联了主键则先删除主键
select count(*) into tm_i from user_constraints where lower(table_name)=Lower('table_name') and lower(constraint_name)=lower('PK_Constraints_name');
if tm_i>0 then
execute immediate 'alter table table_na