还原bak到localdb的问题:The logical database file cannot be found ldf --Exclusive access could not be obtained because the database is in use 

主要环境相关因素:win7,ms sql 2012,ms localdb,msms 2012.

步骤:

1,让DBA给一个bak文件到本地来做测试,DBA按自己的工作流程得到bak文件。

2,在msms 2012中创建同样名称的数据库,按我的想法设置mdf和ldf的路径。

3,,开始用上次已经成功过的脚本开始在msms 2012执行脚本。报错:

The logical database file cannot be found ldf,xxxx.ldf can't find。

      首先说明为什么用脚本而不直接在管理器中通过UI还原,因为我这边安装完LocalDB后,它的master文件在c盘用户文件夹下面,导致总是会有不能访问master数据库的问题。在上次还原文件的时候,这个问题也折腾了一番,不过由于遇到的人多,马上就找到使用脚本的解决方案了。

没理由mdf文件可以找到,但是日志文件找不到啊。网上搜很久,最后有个 哥们说:

I'm having this problem too.  I managed to deduce that it has something to do with the locations of the original data and log files.  If you look at the file list you'll notice that the data and log files from the original database were stored in different locations.  If the files were stored in the same location the restore would work successfully.

If you want to try this out restore the database in a full SQL Server 2012 instance (Standard or better) making sure the data and log files are stored in the same folder.  Make a back-up of that database and restore it in your LocalDb instance.  Now restore the same database on your full SQL Server instance placing the data and log files in separate folders, create a backup, and try to restore this in your LocalDb instance.  You should get the same error message.

I've submitted feedback via Connect: https://connect.microsoft.com/SQLServer/feedback/details/789845.

以上说了两点:

1,本地新加数据库物理文件路径要保持和bak文件中的一致

即是bak中的文件名称和新数据库名称一致,同时bak文件中的mdf和ldf文件的路径和新数据库中的一致。这一点经过本人验证,只需要逻辑名一致就行了。物理路径和名称可以不一样。

如何查看bak文件物理和逻辑结构:

restore filelistonly
 FROM DISK = 'D:worksackupwebxxx.bak'

2,mdf文件和log文件要在同一目录下。

而我这里为什么会出错的原因是,DBA把mdf放在data/*.mdf下,日志放在log/*.ldf下。更牛逼的是他在sql 2012 msms 操作总是成功,导致我没法怀疑他的操作。而在localdb中,它是从mdf来推断ldf路径的,所以总是找不到ldf文件。

最后让DBA把mdf,ldf放同一目录下问题搞定。

附上脚本:

--避免出现:

Alter Database SLdb
  SET SINGLE_USER With ROLLBACK IMMEDIATE

 RESTORE DATABASE dbname
 FROM DISK = 'D:worksackupweb***.bak'
 WITH REPLACE,
 MOVE 'YYYY' TO 'D:demosDbXXXX.mdf',
 MOVE 'YYYY_log' TO 'D:demosDbYYYY_log.ldf',
 STATS = 1
 GO

--再设置回来

alter database *****
set multi_user