Transaction
Whatistransaction?
IsasetofT-SQLstatementsthatareexecutedtogetherasaunitlikeasa
singleT-SQLstatement.IfalloftheseT-SQLstatementsexecuted
successfully,thenatransactioniscommittedandthechangesmadebyT-SQL
statementspermanentlysavedtodatabase
Transactionproperties(ACID)
Atomicity.Associatedmodificationsareanall-or-nothingproposition;eitherallare
doneornonearedone.
requiresthateachtransactionbe"allornothing":ifonepartofthetransactionfails,
thentheentiretransactionfails
Consistency.Afteratransactionfinishes,alldataisinthestateitshouldbein,all
internalstructuresarecorrect,andeverythingaccuratelyreflectsthetransactionthat
hasoccurred.
Isolation.Onetransactioncannotinterferewiththeprocessesofanothertransaction.
Durability.Afterthetransactionhasfinished,allchangesmadearepermanent.
Typeoftransaction
1. Autocommit
2. Implicittransaction
3. Explicittransaction
AutoCommit.EverySQLstatementisitsowntransactionandautomatically
commitswhenitfinishes.ThisisthedefaultmodeinwhichDBServeroperates.
Explicittransaction: Thisapproachprovidesprogrammaticcontrolofthe
transaction,usingtheBEGINTRANandCOMMIT/ROLLBACKTRAN/WORK
commands.
ThemaindifferencebetweenImplicitandExplicittransactionisthatimplicit
transactionisauto,controlledbySQLServerEngineandstatementlevel
transaction,whereasexplicittransactionisuserdefinedandbatch-scoped
transaction
Implicittransaction:
Inthismode,whenyouissuecertainSQLcommands,DBServer
automaticallystartsatransaction.Youmustfinishthetransactionby
explicitlyissuingtheCOMMIT/ROLLBACKTRAN/WORKcommands.
everyDDL(CREATE,ALTER,DROP,TRUNCATE),DML(INSERT,
UPDATE,DELETE)statements.AlltheseT-SQLstatementsrunsunderthe
implicittransaction
Transaction control
COMMIT:tosavethechanges.
ROLLBACK:torollbackthechanges.
SAVEPOINT:createspointswithingroupsoftransactionsinwhichtoROLLBACK
Thecommitcommand
•TheCOMMITcommandisthetransactionalcommandusedtosave
changesinvokedbyatransactiontothedatabase.
•TheCOMMITcommandsavesalltransactionstothedatabasesincethelast
COMMITorROLLBACKcommand
The Rollback command
•TheROLLBACKcommandisthetransactionalcommandusedtoundo
transactionsthathavenotalreadybeensavedtothedatabase.
•TheROLLBACKcommandcanonlybeusedtoundotransactionssincethe
lastCOMMITorROLLBACKcommandwasissued.
The save point
•ASAVEPOINTisapointinatransactionwhenyoucanrollthetransaction
backtoacertainpointwithoutrollingbacktheentiretransaction.
Syntax transaction
• BEGINTRAN[SACTION]
• Statement1
• Statement2
• etc…
• COMMIT[TRAN[SACTION]
OR
• ROLLBACK[TRAN[SACTION]
Example:-
ThankU4Discussing

Transaction