[mssql] Transact-SQL, DB detach attach

2020. 10. 14. 08:00IT/DB

version: Microsoft SQL Server 2012 (SP3)

 

! If the procedure is running or using DB, you can't detach the Database.
! First, you have to check the Service in operation. After that, switching the database offline.

use master;
GO
EXEC sp_detach_db @dbname = N'mydb';
GO

 

! After detach the databse, you can copy the mdf and ldf file.

 

! if the file copy is finished normally, you can attach the DB with new path.

USE master;
GO
CREATE DATABASE PlatformService
    ON (FILENAME = 'H:\SQL_DATA3\mydb.mdf'),
    (FILENAME = 'H:\SQL_DATA3\mydb_log.ldf')
    FOR ATTACH;
GO

 

! When the tasks are completed successfully, Check that the DB is working properly.
! If you switched the database offline, you have to switching the db status to online.