有什么方法可以快速判断 .mdf 文件附加了哪个数据库(如果有)?
假设SQL Server 2005 / 2008具有大量数据库。有没有办法快速判断哪个数据库(如果有)附加到特定的 .mdf 文件?
随着时间的推移,我们删除了一些数据库,并希望清理一些残留的 .mdf 以清理服务器上的空间。目前我所知道的唯一方法是在 Management Studio 中逐一查看每个数据库的属性,并列出它们所附加的文件的列表。寻找比这更有效的东西(如果有的话)。
Assume SQL Server 2005 / 2008 with a large number of databases. Is there any way to quickly tell which database, if any, is attached to a particular .mdf file?
We've dropped some databases over time and would like to clean up some lingering .mdf's to clear up space on the server. Currently the only way I know of is to look at the properties of each database, one by one, in Management Studio and make a list of the files they're attached to. Looking for something a little more efficient than this, if anything exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
sys.master_files 对于该数据库的第一个文件 (id = 1),每个数据库包含一行。也就是说,每个数据库的系统表将始终位于 fileid = 1
这就是您所需要的:
sys.master_files contains one row per database for the first file (id = 1) for that database. That is, system tables will always be in fileid = 1 for each database
This is all you need:
这可能会有所帮助。
This may help.
将列出系统上已知的所有数据库的所有文件。
Will list all the files of all the databases known on the system.
您还可以使用 OrcaMDF 来实现此目的:
这将允许您查询 mdf 的数据库名称,而无需附加将它们发送到数据库服务器。请注意,这应该在主数据文件上完成,以防有多个文件。免责声明 - 我是 OrcaMDF 的作者。
循环遍历数据目录中的所有文件,很容易将其与 sys.databases 连接并查看哪些文件不匹配,因此是未附加的 mdf 文件。
编辑:在我的博客上发布了一个更彻底的示例: http://improve.dk/archive/2011/05/19/checking-which-database-is-stored-in-a-deattached-mdf-file.aspx
You could also use OrcaMDF for this:
This'll allow you to query the mdf's for their database name without attaching them to the database server. Note that this should be done on the primary data file, in case there are multiple files. Disclaimer - I'm the author of OrcaMDF.
Looping through all files in the data directory, it'd be easy to join that with sys.databases and see which ones don't match up, and are hence non-attached mdf files.
Edit: Posted a more thorough example on my blog: http://improve.dk/archive/2011/05/19/checking-which-database-is-stored-in-a-deattached-mdf-file.aspx
低技术解决方案...将 mdf 文件移动到另一个位置。如果它已附加,SQL Server 不会让您移动它:)
从命令提示符
所有未使用的文件将被移动到 UnusedDBFiles。
Low tech solution... move the mdf file to another location. If it is attached, SQL server would not let you move it :)
From command prompt
All the unused files would be moved to UnusedDBFiles.