Sql Server change data and log path of existing database Sql Server change data and log path of existing database sql sql

Sql Server change data and log path of existing database


First, detach database:

USE master;GO-- Important! We need to drop the existing connections.ALTER DATABASE DBName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;GOEXEC 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 .ldfGO

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.