I create database "Test" in folder "d:\test". Database files are "d:\test\Test.mdf" and "d:\Test\Test_log.ldf". I detach database from MS SQL Server 2008 R2, copy all files to new folder ("d:\test_new"), delete log file ("d:\test_new\Test_log.ldf"), and try to attach database again from new location. When I use SQL Server Management Studio, and choose "d:\test_new\Test.mdf" file, it determines that log file is located in "d:\test\Test_log.ldf" (old location). How can I attach this database with rebuilding log in new location? Just imagine, that I cannot copy ldf file again to new location, and that it is still available there, so SQL Server see it anyway. I want to say to SQL Server – "please, forget that log file, and create new log file here". It’s be better if you help me with T-SQL script, but if it will be steps in Management studio – I will convert it to script myself.
What I had tried already:
1.
CREATE DATABASE [test]
ON ( FILENAME = N'D:\test_new\test.mdf' )
FOR ATTACH_REBUILD_LOG
attaches log file from old location (FOR ATTACH – the same)
2.
CREATE DATABASE [test]
ON ( FILENAME = N'D:\test_new\test.mdf' )
LOG ON ( FILENAME = N'D:\test_new\test_log.ldf' )
FOR ATTACH_REBUILD_LOG
returns an error: Unable to open the physical file "D:\test_new\test_log.ldf". Operating system error 2: "2(File not found.)".
3.
sp_attach_db and sp_attach_single_file_db
was tried too. And I even had checked their source codes – they just create dynamic SQL and call CREATE DATABASE … FOR ATTACH statement.
The question is slowly changed to: "Is it possible?"
UPDATE
Well, it looks like it’s not possible with current versions of SQL Server. If anybody knows a way to do it – please, I will be very pleased to know it too!
Edit2: To my knowledge, it is not possible for SQL Server to recreate a log file. It can shrink the ldf, but not create it when only the mdf exists.
When you copy your files from
d:\test\tod:\test_new\, do not delete thed:\test_new\Test_log.ldf.Leave the log file there, because you cannot reattach the new DB without that log file. Afterwards, you can shrink that log to a minimum size.
So, to synthesize:
d:\test\tod:\test_new\and leave the logfile there.
create databasescript that you posted in your question (point 2)..
To find out what
logicalFileNameis, runsp_helpfile, that will give you the logical file name for your log file:more info here
Edit:
I think you need first to detach the
testdatabase from the old location:(You might create a script that does it all, from the following commands)
Then copy the files to the new location.
Next, attach the
testDB to the new path location:to test if the new database was successfully attached:
If there are no errors after the
gocommand, then all is okHope this helps
Microsoft article on how to move files