Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server change data and log path of existing database

I am having a SQL Server 2008 installation with almost 15 databases running on it. Now due to scarcity of space I would like to move the data path to another drive. What is the best practice for this. Please explain in details if including any SQL commands as I'm relatively new to SQL Server administration.

Note - I have already changed the path in SQL server properties from SQL Management Studio 2008, to the new path. But I would also like the existing databases to reside in the new path.

like image 715
Soham Dasgupta Avatar asked Jul 28 '11 09:07

Soham Dasgupta


People also ask

How do I change the location of SQL Server data and log files?

View or change the default locations for database filesIn Object Explorer, right-click on your server and click Properties. In the left panel on that Properties page, click the Database settings tab. In Database default locations, view the current default locations for new data files and new log files.

How do I move data and log files in SQL Server?

In SQL Server, you can move system and user databases by specifying the new file location in the FILENAME clause of the ALTER DATABASE statement. Data, log, and full-text catalog files can be moved in this way. This may be useful in the following situations: Failure recovery.


2 Answers

First, detach database:

USE master;
GO
-- Important! We need to drop the existing connections.
ALTER DATABASE DBName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
EXEC sp_detach_db @dbname = N'DBName';
GO

Next step - copy files .mdf and .ldf of this database files to new location

And then attaching the database:

USE master;
EXEC sp_attach_db @dbname = N'dbName', 
@filename1 = N'',  --path do .mdf
@filename2 = N'';  --path to .ldf
GO

If you don't want to attach and detach all databases one-by-one, you can generate SQL script to attach and detach all databases you need (execept system, of course), using curosr that searches in sys.databases dynamic management view. But don't forget to copy the database files.

like image 53
Alex_L Avatar answered Oct 22 '22 11:10

Alex_L


One way is to detach and attach.

As for commands/steps, see the MSDN article "How to: Move a Database Using Detach and Attach (Transact-SQL)"

like image 26
gbn Avatar answered Oct 22 '22 12:10

gbn