Steps to copy .mdf and .ldf files of database to another location

If you try to copy .mdf  and .lfd file to new location, sql server not allow you to do so, it will through the error. For that you need to follow certain steps. Below are the steps which will tell you how to achieve this task.

STEP 1:  Alter Database to Single User.
To copy a log of database you need to Detach the log file from database so for that you need to make database Single User First.

Syntax:

ALTER DATABASE Database_Name
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;

STEP 2:  kill other session of database
If you switch database mode multiple to single you need to kill other session to use single mode database and do some operations.

Below is the query which is returns current session of the database

Syntax:

select d.name, d.dbid, spid, login_time, nt_domain, nt_username, loginame
from sysprocesses p inner join sysdatabases d on p.dbid = d.dbid
where d.name = 'Database_Name'

Above query will return session id which are using same database. Below is the query to kill other session

Syntax:

kill SessionID;


Ex: kill 61


STEP 3: Detach Database .ldf and .mdf
Syntax:


EXEC MASTER.dbo.sp_detach_db @dbname = N'Database_Name'
GO

Now you can copy mdf and ldf file of database 

To create new database using moved mdf file, use below query:
Syntax:

CREATE DATABASE [DatabaseName] ON
( FILENAME = N'F:\loc2\DatabaseName.mdf' ),
( FILENAME = N'F:\loc2\DatabaseName_log.ldf' )
FOR ATTACH
GO

If you want to attached to the Existing database then follow following steps:

1.Right click to Databases(Root to the all databases)
2.Select Attach
3.Select mdf and ldf file location and click on to attached mdf file to existing database.


Comments

Popular posts from this blog

Connecting Remote server with Local Server

MDX Error handling tricks

JSON_Automated_stored_procedure