基础知识
查询现有数据库列表
use master
go
select db_name(database_id) as [Database Name],type_desc as [File Type], physical_name as [Database File Location] from sys.master_files
附加数据库(TSQL)
方法一
USE [master]
GO
create database <DatabaseName> ON
(name='LogicalName of the Data file', FileName='Data File Name'),
(name='LogicalName of the Log file', FileName='Log File Name')
FOR ATTACH;
方法二
USE [master]
GO
EXEC sp_attach_db @dbname = N'DatabaseName',
@filename1 = '<Location of the database file>',
@filename2 = '<Location of the Log file>';
分离数据库(TSQL)
EXEC sp_detach_db 'AdventureWorks2012', 'true';
实际应用
实际应用中,如果我们有多个数据库,我们就需要批量附加,大概的思路如下:
- 选择文件夹,遍历文件夹下的所有mdf文件,并找到对应的ldf文件
- 构造单个的TSQL语句(附加或分离)
- 将构造好的TSQL语句执行即可
参考资料:
3. Different methods to attach SQL Server MDF files
4. sp_detach_db (Transact-SQL)