您的位置:首页 > 数据库 > Oracle

Oracle 临时表

2009-10-20 20:48 211 查看
一.临时表说明

OracleDatabasetemporarytablesholddatathatexistsonlyforthedurationofatransactionorsession.Datainatemporarytableisprivatetothesession,whichmeansthateachsessioncanonlyseeandmodifyitsowndata.

Temporarytablesareusefulinapplicationswherearesultsetmustbebuffered.Forexample,aschedulingapplicationenablescollegestudentstocreateoptionalsemestercourseschedules.Eachscheduleisrepresentedbyarowinatemporarytable.Duringthesession,thescheduledataisprivate.Whenthestudentdecidesonaschedule,theapplicationmovestherowforthechosenscheduletoapermanenttable.Attheendofthesession,thescheduledatainthetemporarydataisautomaticallydropped.

TemporaryTableCreation
TheCREATEGLOBALTEMPORARYTABLEstatementcreatesatemporarytable.TheONCOMMITclausespecifieswhetherthetabledataistransaction-specific(default)orsession-specific.

Unliketemporarytablesinsomeotherrelationaldatabases,whenyoucreateatemporarytableinanOracledatabase,youcreateastatictabledefinition.Thetemporarytableisapersistentobjectdescribedinthedatadictionary,butappearsemptyuntilyoursessioninsertsdataintothetable.Youcreateatemporarytableforthedatabaseitself,notforeveryPL/SQLstoredprocedure.

Becausetemporarytablesarestaticallydefined,youcancreateindexesforthemwiththeCREATEINDEXstatement.Indexescreatedontemporarytablesarealsotemporary.Thedataintheindexhasthesamesessionortransactionscopeasthedatainthetemporarytable.Youcanalsocreateaviewortriggeronatemporarytable.
--临时表可以创建临时的索引,视图,触发器。

SegmentAllocationinTemporaryTables
Likepermanenttables,temporarytablesaredefinedinthedatadictionary.Temporarysegmentsareallocatedwhendataisfirstinserted.Untildataisloadedinasessionthetableappearsempty.Temporarysegmentsaredeallocatedattheendofthetransactionfortransaction-specifictemporarytablesandattheendofthesessionforsession-specifictemporarytables.


临时表只在Oracle8i以及以上产品中支持。ORACLE数据库除了可以保存永久表外,还可以建立临时表temporarytables。这些临时表用来保存一个会话SESSION的数据,或者保存在一个事务中需要的数据。当会话退出或者用户提交commit和回滚rollback事务的时候,临时表的数据自动清空,但是临时表的结构以及元数据还存储在用户的数据字典中。

Oracle的临时表创建之后基本不占用表空间,临时表并非存放在用户的表空间中,而是存放在Schema所指定的临时表空间中。如果你没有指定临时表(包括临时表的索引)存放的表空的时候,你插入到临时表的数据是存放在ORACLE系统的临时表空间中(TEMP)。

可以对临时表创建索引,视图,触发器,可以用export和import工具导入导出表的定义,但是不能导出数据。表的定义对所有的会话可见。建立在临时表上的索引也是临时的,也是只对当前会话或者事务有效.

尽管对临时表的DML操作速度比较快,但同样也是要产生RedoLog,只是同样的DML语句,比对PERMANENT的DML产生的RedoLog少。

临时表的不足之处:
1.不支持lob对象,这也许是设计者基于运行效率的考虑,但实际应用中确实需要此功能时就无法使用临时表了。
2.不支持主外键关系

特性和性能(与普通表和视图的比较)
 1.临时表只在当前连接内有效
 2.临时表不建立索引,所以如果数据量比较大或进行多次查询时,不推荐使用
 3.数据处理比较复杂的时候时表快,反之视图快点
4.在仅仅查询数据的时候建议用游标:opencursorfor'sqlclause';

临时表的应用:
对于一个电子商务类网站,不同消费者在网站上购物,就是一个独立的SESSION,选购商品放进购物车中,最后将购物车中的商品进行结算。也就是说,必须在整个SESSION期间保存购物车中的信息。同时,还存在有些消费者,往往最终结账时放弃购买商品。如果,直接将消费者选购信息存放在最终表(PERMANENT)中,必然对最终表造成非常大的压力。因此,对于这种案例,就可以采用创建临时表(ONCOMMITPRESERVEROWS)的方法来解决。数据只在SESSION期间有效,对于结算成功的有效数据,转移到最终表中后,ORACLE自动TRUNCATE临时数据;对于放弃结算的数据,ORACLE同样自动进行TRUNCATE,而无须编码控制,并且最终表只处理有效订单,减轻了频繁的DML的压力。
TempTable的另一个应用,就是存放数据分析的中间数据。


二.创建临时表
2.1CreatingaTemporaryTable
Temporarytablesareusefulinapplicationswherearesultsetistobebuffered(temporarilypersisted),perhapsbecauseitisconstructedbyrunningmultipleDMLoperations.Forexample,considerthefollowing:
AWeb-basedairlinesreservationsapplicationallowsacustomertocreateseveraloptionalitineraries.Eachitineraryisrepresentedbyarowinatemporarytable.Theapplicationupdatestherowstoreflectchangesintheitineraries.Whenthecustomerdecideswhichitineraryshewantstouse,theapplicationmovestherowforthatitinerarytoapersistenttable.
Duringthesession,theitinerarydataisprivate.Attheendofthesession,theoptionalitinerariesaredropped.
Thedefinitionofatemporarytableisvisibletoallsessions,butthedatainatemporarytableisvisibleonlytothesessionthatinsertsthedataintothetable.

UsetheCREATEGLOBALTEMPORARYTABLEstatementtocreateatemporarytable.TheONCOMMITclauseindicatesifthedatainthetableistransaction-specific(thedefault)orsession-specific,theimplicationsofwhichareasfollows:


[thead]
[/thead]

ONCOMMITSetting

Implications
DELETEROWS
Thiscreatesatemporarytablethatistransactionspecific.Asessionbecomesboundtothetemporarytablewithatransactionsfirstinsertintothetable.Thebindinggoesawayattheendofthetransaction.Thedatabasetruncatesthetable(deleteallrows)aftereachcommit.
PRESERVEROWS
Thiscreatesatemporarytablethatissessionspecific.Asessiongetsboundtothetemporarytablewiththefirstinsertintothetableinthesession.ThisbindinggoesawayattheendofthesessionorbyissuingaTRUNCATEofthetableinthesession.Thedatabasetruncatesthetablewhenyouterminatethesession.
Thisstatementcreatesatemporarytablethatistransactionspecific:
CREATEGLOBALTEMPORARYTABLEadmin_work_area

(startdateDATE,

enddateDATE,

classCHAR(20))

ONCOMMITDELETEROWS;


Indexescanbecreatedontemporarytables.Theyarealsotemporaryandthedataintheindexhasthesamesessionortransactionscopeasthedataintheunderlyingtable.
Bydefault,rowsinatemporarytablearestoredinthedefaulttemporarytablespaceoftheuserwhocreatesit.However,youcanassignatemporarytabletoanothertablespaceuponcreationofthetemporarytablebyusingtheTABLESPACEclauseofCREATEGLOBALTEMPORARYTABLE.Youcanusethisfeaturetoconservespaceusedbytemporarytables.
Forexample,ifyoumustperformmanysmalltemporarytableoperationsandthedefaulttemporarytablespaceisconfiguredforsortoperationsandthususesalargeextentsize,thesesmalloperationswillconsumelotsofunnecessarydiskspace.Inthiscaseitisbettertoallocateasecondtemporarytablespacewithasmallerextentsize.

Thefollowingtwostatementscreateatemporarytablespacewitha64KBextentsize,andthenanewtemporarytableinthattablespace.

CREATETEMPORARYTABLESPACEtbs_t1

TEMPFILE'tbs_t1.f'SIZE50mREUSEAUTOEXTENDON

MAXSIZEUNLIMITED

EXTENTMANAGEMENTLOCALUNIFORMSIZE64K;


CREATEGLOBALTEMPORARYTABLEadmin_work_area

(startdateDATE,

enddateDATE,

classCHAR(20))

ONCOMMITDELETEROWS

TABLESPACEtbs_t1;




2.2创建临时表
Oracle临时表,有两种类型:
会话级的临时表
事务级的临时表。

2.2.1.会话级的临时表
因为这这个临时表中的数据和你的当前会话有关系,当你当前SESSION不退出的情况下,临时表中的数据就还存在,而当你退出当前SESSION的时候,临时表中的数据就全部没有了,当然这个时候你如果以另外一个SESSION登陆的时候是看不到另外一个SESSION中插入到临时表中的数据的。即两个不同的SESSION所插入的数据是互不相干的。
当某一个SESSION退出之后临时表中的数据就被截断(truncatetable,即数据清空)了。
注:这里要说明的是,ORACLETruncate掉的数据仅仅是分配给不同Session或Transaction的TempSegment上的数据,而不是将整张表数据TRUNCATE掉。当Commit的时候则数据还在,当Rollback的时候则数据也是一样被回滚.

会话级的临时表创建方法:
SQL>CREATEGLOBALTEMPORARYTABLETABLE_NAME(<columnspecification>)
ONCOMMITPRESERVEROWS;
或者
SQL>CREATEGLOBALTEMPORARYTABLETABLE_NAMEONCOMMITPRESERVEROWSASSELECT*FROMTABLE_NAME;

示例:
SQL>CREATEGLOBALTEMPORARYTABLETT(IDNUMBER(2))ONCOMMITPRESERVEROWS;
表已创建。
SQL>SELECT*FROMTT;
未选定行
SQL>INSERTINTOTTVALUES(1);
已创建1行。
SQL>COMMIT;
提交完成。
SQL>SELECT*FROMTT;
ID
----------
1
SQL>INSERTINTOTTVALUES(2);
已创建1行。
SQL>SELECT*FROMTT;
ID
----------
1
2
SQL>ROLLBACK;
回退已完成。
SQL>SELECT*FROMTT;
ID
----------
1

2.2.2事务特有的临时表(默认类型)
该临时表与事务相关,当进行事务提交或者事务回滚的时候,临时表中的数据将自行被截断,其他的内容和会话级的临时表的一致(包括退出SESSION的时候,事务级的临时表也会被自动截断)。一旦COMMIT后,数据就被自动TRUNCATE掉了.

事务级临时表的创建方法:
SQL>CREATEGLOBALTEMPORARYTABLETABLE_NAME(<columnspecification>)
ONCOMMITDELETEROWS;

或者
SQL>CREATEGLOBALTEMPORARYTABLETABLE_NAMEONCOMMITDELETEROWSASSELECT*FROMTABLE_NAME;

CREATEGLOBALTEMPORARYTABLETABLE_NAME;在不指明类型的情况下,默认为事务临时表。

SQL>CREATEGLOBALTEMPORARYTABLETT2(IDNUMBER(2))ONCOMMITDELETEROWS;
表已创建。
SQL>SELECT*FROMTT2;
未选定行
SQL>INSERTINTOTT2VALUES(1);
已创建1行。
SQL>SELECT*FROMTT2;
ID
----------
1
SQL>COMMIT;
提交完成。
SQL>SELECT*FROMTT2;
未选定行
SQL>






-------------------------------------------------------------------------------------------------------
Blog:http://blog.csdn.net/tianlesoftware
Email:dvd.dba@gmail.com
DBA1群:62697716(满);DBA2群:62697977(满)DBA3群:62697850(满)
DBA超级群:63306533(满);DBA4群:83829929DBA5群:142216823
DBA6群:158654907聊天群:40132017聊天2群:69087192
--加群需要在备注说明Oracle表空间和数据文件的关系,否则拒绝申请
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: