事务学习

===========================
1.transaction control
默认由修改数据开始(tx_lock),手工:set transaction |dbms_transaction
由commit,rollback结束(rollback to savepoin不会结束transaction)

a)默认statement-level atomicity 如
savepoint statement1;
insert into t values(1);
if error then rollback to statement1;
savepoint statment2;
insert into t values(2);
if error then rollback to statement2;

b)procedure level atomicity
begin
  proce1;
end; 等价于
begin
savepoint sp;
  proce1;
exception when others then 
  rollback to sp;
end;
保持procedure操作一致性
=======
当手动写
begin
  proce1;
exception when others then
  null;--则回到statement-level,错误不处理
end;

2.transaction习惯
a)尽量短
b)大业务切割成定期(比如1000个)分批提交
c)
--创建index
create index i_wwm on twwm(object_name);
exec dbms_stats.gather_table_stats('SYS','TWWM',cascade => true);
--非自动增长undo(多次commit并不节省undo tablespace)
create undo tablespace undo_small 
datafile 'd:\1.dbf' size 2m 
autoextend off;
--使用
alter system set undo_tablespace=undo_small;

begin 
	for r in(select rowid rid,rownum rnum,object_name from twwm) loop--置于for循环
		update twwm set object_name=lower(r.object_name) where rowid=r.rid;
		if(mod(r.rnum,100)=0) then
			commit;
		end if;
	end loop;
	commit;
end;
3.distributed transactions
一个transaction可以连接多个数据库db_link

4.自治transactions(内部transaction),不影响外部

pragma autonomous_transaction (编译指示)
set timing off

select sq_aaa.nextval from dual默认用到autonomous transactions,不能会回滚


----------
create or replace procedure Autonomous_Insert 
as
	pragma autonomous_transaction;
begin
	insert into t values('Autonomous Insert');--内部事务
	commit;
end;

begin 
	insert into t values('Anonymous Block');
	Autonomous_Insert;--内部commit不对外部影响
	rollback;
end;

-----------------------------
create table audit_tab(
	username varchar2(30) default user,
	timestamp date default sysdate,
	msg varchar2(4000)
);

create or replace trigger t_emp_audit
	before update on emp for each row
declare
	pragma autonomous_transaction;
	i_cnt number;
begin
	select count(*) into i_cnt from dual 
	where exist(select null from emp where empno=:new.empno
		start with mgr=(select empno from emp where ename=user)
		connect by prior empno=mgr;
	if(i_cnt=0) then
		insert into audit_tab(msg) values('Attempt to update '||new.empno);
		commit;--提交不受外部影响
		raise_application_error(-20001,'Access Deniedd!');
	end if;
end;

b)pragma automomous_transaction用在方法,函数中
savepoint a; rollback to a;可支持精确点
savepoint回滚之后的预计,保留savepoint,其后的savepoint删除;释放该锁,之前的锁保留;

c)对update,delete可能出现的锁
for update...nowait

你可能感兴趣的:(sql,C++,c,C#,Access)