You are on page 1of 9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

HowtoAttachaSQLServerDatabasewithouta
TransactionLogandwithOpenTransactions
By:DanielFarina|ReadComments(12)|RelatedTips:More>DatabaseAdministration

Problem
YouwanttoattachaSQLServerdatabasethatdoesnothavethetransactionlogfileandyougetthefollowing
errorwhenyoutrytoattachthedatafile:
"Thelogcannotberebuiltbecausetherewereopentransactions/userswhenthedatabasewasshutdown,no
checkpointoccurredtothedatabase,orthedatabasewasreadonly.Thiserrorcouldoccurifthetransactionlog
filewasmanuallydeletedorlostduetoahardwareorenvironmentfailure."
InthistipIwillshowhowyoucansuccessfullyattachadatabasewhenyougetthiserror.

Solution
HereIwillcoverthenotsouncommonscenariowheresomeonegivesyouaSQLServerdatabasetoattachto
yourinstance,butonlygivesyouthe*.mdffile.Unfortunately,whenyoutrytoattachthedatabasetheSQL
Serverenginecomplainsaboutthemissingtransactionlogandabortstheattachmentprocess.

TestEnvironmentSetup
FirstwewillcreateoursampledatabaseandsettherecoverymodeltoFullbyrunningthescriptsbelowinSQL
ServerManagementStudio.
USE[master]
GO
CREATEDATABASE[TestDB]
CONTAINMENT=NONE
ONPRIMARY
(NAME=N'TestDB_file1',

FILENAME=N'E:\MSSQL\TestDB_1.mdf',

SIZE=128MB,

MAXSIZE=UNLIMITED,

FILEGROWTH=64MB)
LOGON
(NAME=N'TestDB_log_file1',

FILENAME=N'E:\MSSQL\TestDB_1.ldf',

SIZE=8MB,

MAXSIZE=2048GB,

FILEGROWTH=8MB)
https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

1/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

GO
ALTERDATABASETestDBSETRECOVERYFULL
GO

Thenextscriptwillcreateoursampletable.
USETestDB
GO
SELECT*
INTOTestTable
FROMsys.objects

Nowwearegoingtoaddsomesampledata.Wewanttheinsertstatementtotakeenoughtimetoletusforcethe
shutdownofthetestinstancewhileitisstillrunning.Thiswillletthedatabasebeinaninconsistentstateneeding
toperformrecoveryatthenextdatabasestartup.
USETestDB;
GO
INSERTINTOdbo.TestTable
SELECTa.*
FROMTestTablea
CROSSJOINsys.objectsb
CROSSJOINsys.objectsc
CROSSJOINsys.objectsd

InanotherwindowinSQLServerManagementStudioexecutethefollowingstatementtoforcetheinstance
shutdown.
SHUTDOWNWITHNOWAIT

Afterstoppingtheinstance,deletethelogfilethenstartuptheSQLServerservice.IfyourefreshtheDatabases
viewinSQLServerManagementStudioyouwillseethatourtestdatabaseisinaccessiblebecauseitismarked
asRecoveryPending,asshownonthenextimage.

https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

2/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

Atthispointwehaveanorphanedandinconsistentdatabasefile.
First,letscleanthesystemcatalogbydroppingthedatabase.Wemustsetthedatabaseofflinetocopyor
renamethedatafilethatwillbethesubjectforourtests.
USEmaster
GO
ALTERDATABASETestDBSETOFFLINE
GO

Thenwemustcleanthesystemcatalogmetadatabydroppingthedatabase.
USEmaster
GO
DROPDATABASETestDB
GO

TryingtoAttachtheDamagedSQLServerDatabase
Whenyouareaskedtoattachadatabasewithonedatafileandnolog,thefirstthingthatmaycometomindis
theoldanddeprecatedsp_attach_single_file_db.
USEmaster
https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

3/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

GO
EXECsys.sp_attach_single_file_db@dbname='TestDB',
@physname=N'E:\MSSQL\TestDBCopy.mdf'
GO

Butafteryouexecutethepreviousscriptyouwillseethatitfailswiththiserrormessage:
"Thelogcannotberebuiltbecausetherewereopentransactions/userswhenthedatabasewasshutdown,no
checkpointoccurredtothedatabase,orthedatabasewasreadonly.Thiserrorcouldoccurifthetransactionlog
filewasmanuallydeletedorlostduetoahardwareorenvironmentfailure."
Seetheimagebelowasapointofreference.

Sincesp_attach_single_file_dbisdeprecatedandhasbeenreplacedwithCREATEDATABASE..FORATTACH,
letstrythistoseeifwehavemoreluck.
USE[master]
GO
CREATEDATABASE[TestDB]ON
(FILENAME=N'E:\MSSQL\TestDBCopy.mdf')
FORATTACH_REBUILD_LOG
GO

Wefacethesameerrormessagetellingusthatthelogofthedatabasecannotberebuilt.

https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

4/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

Atthispointwetriedeverything,butthereisanotherway,maketheenginebelievethatthedatabaseisalready
attached.

AttachingtheDamagedSQLServerDatabase
Thefirststepistocreateanewdatabase.
USE[master]
GO
CREATEDATABASE[TestDB_Repair]
CONTAINMENT=NONE
ONPRIMARY
(NAME=N'TestDB_Repair_file1',

FILENAME=N'E:\MSSQL\TestDB_Repair_1.mdf',

SIZE=8MB,

MAXSIZE=UNLIMITED,
FILEGROWTH=64MB)

LOGON
(NAME=N'TestDB_Repair_log_file1',

FILENAME=N'E:\MSSQL\TestDB_Repair_1.ldf',
SIZE=8MB,

MAXSIZE=2048GB,

FILEGROWTH=32MB)

GO

Nowwesetthedatabaseoffline.
USEmaster
GO
ALTERDATABASE[TestDB_Repair]SETOFFLINEWITHROLLBACKIMMEDIATE
GO

Atthispointwecanchangethefilelocationofournewdatabasetopointtoourorphanedmdffileandsetthe
https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

5/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

locationofthelogfiletoanonexistentfile.
USEmaster
GO

ALTERDATABASE[TestDB_Repair]MODIFYFILE(NAME='TestDB_Repair_file1',FILENAME='E:\MSSQL\TestDBCopy.mdf

ALTERDATABASE[TestDB_Repair]MODIFYFILE(NAME='TestDB_Repair_log_file1',FILENAME='E:\MSSQL\TestDBCopy
GO

Letsbringthedatabasebackonline.
USEmaster
GO
ALTERDATABASE[TestDB_Repair]SETONLINE
GO

WedonthavetobeSQLServergurustoknowthatthepreviousscriptwillfail.Butifyoutakealookattheerror
messageofthenextscreencaptureyouwillseethatwhenSQLServerdidntfindthetransactionlogfile
(rememberthatwechangedthesystemcatalogtopointtoafilethatdoesntexist)ittriestorebuildit.Andof
courseitsattempttorebuildthelogfailswiththesameerrormessagewehadwhiletryingtoattachourorphaned
*.mdffile,onlyinthiscasethe*.mdfwassuccessfullyattachedleavingusonestepclosertoourobjective.

RebuildingtheSQLServerTransactionLog
NowyouwillseethatitisntverycomplicatedtorebuildtheSQLServertransactionlog,butyoumustacceptthe
factthatyouwilllosedata.Infact,youshouldusethismethodtorecoveradamageddatabaseifrestoringthe
databasefromabackupisnotpossible.Thereasonbehindthisisthatyoucanlosedataotherthanthelastuser
activity.Forexample,ifatransactionwasupdatinganindexandtheupdateoperationperformedapagesplit,you
maylosepreviouslycommittedtransactionsthatwerenolongerinthetransactionlogbecausepagesplitsarea
loggedoperation.
https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

6/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

ThenextscriptincludesseveralcommandsthatIputtogethertobringoursampledatabasebackonline.Further
onIwillexplainthecommandsandwhyIdecidedtoexecutealloftheminasinglescript,butfirstlet'stakea
look.
USEmaster
GO
DBCCTRACEON(3604)
GO
ALTERDATABASETestDB_RepairSETEMERGENCY
GO
ALTERDATABASETestDB_RepairSETSINGLE_USER
GO
DBCCCHECKDB('TestDB_Repair',REPAIR_ALLOW_DATA_LOSS)WITHALL_ERRORMSGS
GO
ALTERDATABASETestDB_RepairSETMULTI_USER
GO

ThefirststepinthepreviousscriptistosendalloutputfromtheDBCCcommandstothequeryresultsinsteadof
totheerrorlog.Thenexttwostepssetthedatabasetoemergencymodeandsingleusermoderespectively,so
wecanexecuteDBCCCHECKDBwiththeREPAIR_ALLOW_DATA_LOSSoption.Finallythelastcommandisto
bringthedatabasebacktomultiusermode.
Onthenextimageyoucanseeascreencaptureoftheexecutionofthepreviousscript.Imarkedinredoneofthe
outputmessageswhichstatesthattheerrorloghasbeenrebuilt.

https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

7/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

NextSteps
BeforerunninganintegritycheckofyourdatabasesIrecommendyoureadthistip:SQLServerDatabase
IntegrityChecksChecklist.
TogetadetailedexplanationaboutDBCCCHECKDBtakealookatthistip:Minimizeperformanceimpactof
SQLServerDBCCCHECKDB.
ThistipwillexplainhowEmergencymodeworks:UsingtheEmergencyStateforaCorruptSQLServer
Database.
Ifyoudontknowthedifferencesbetweenrecoverymodelstakealookatthistutorial:SQLServerRecovery
ModelsTutorial.
Youcanlearntransactionlogbasicsandmoreinthistutorial:IntroductiontotheSQLServerTransactionLog.
Hereyoucanlearnaboutattachinganddetachingdatabases:UpgradingtoSQLServer2008UsingDetachand
AttachOperations.

LastUpdate:4/22/2015

Abouttheauthor
DanielFarinawasborninBuenosAires,Argentina.Selfeducated,sincechildhoodheshowedapassionforlearning.
https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

8/9

4/20/2016

HowtoAttachaSQLServerDatabasewithoutaTransactionLogandwithOpenTransactions

Viewallmytips

RelatedResources

MoreSQLServerDBATips...

Copyright(c)20062016EdgewoodSolutions,LLCAllrightsreserved
Somenamesandproductslistedaretheregisteredtrademarksoftheirrespectiveowners.

https://www.mssqltips.com/sqlservertip/3579/howtoattachasqlserverdatabasewithoutatransactionlogandwithopentransactions/

9/9

You might also like