TSQL - How to move all database files to new location, script to move files.
Post date: Jan 23, 2014 9:41:14 AM
If you want to move the physical files of your database you will need to follow a few steps.
Don't trust this script, always review any scripts you find online.
If you are moving files for multiple databases simply adjust the WHERE clause of the script to include all of them.
- Put the database in offline mode
- Move or copy the logs and database physical files to the new location
- Yes, this need to be done manually by copying files between disks.
- Make sure that sql server have access to the file in the new location. Check the security rights of the file to make sure. This especially if the file was copied rather than moved.
- Alter the script below to point the logLocation and dataLocation to the folder where your files now exist
- Run this script which will create scripts to alter the database file location
- Run the generated script
- Put the database in online mode
USE master;GODECLARE @logLocation VARCHAR(4000) = 'I:\log\';DECLARE @dataLocation VARCHAR(4000) = 'J:\dbdata\';SELECT 'ALTER DATABASE '+db_name(database_id)+' MODIFY FILE ( NAME = '+name+', FILENAME = '''+case type_desc when 'log' THEN @logLocation + physicalFile when 'rows' then @datalocation + physicalFile end+''');'FROM sys.master_filescross APPLY( SELECT SUBSTRING(physical_name, LEN(physical_name) - CHARINDEX('\',REVERSE(physical_name)) + 2, CHARINDEX('\',REVERSE(physical_name)))) files(physicalFile)WHERE database_id = DB_ID(N'AdventureWorks2012');GO