Script to change the location of the SQL Server database file

I need to change all the file locations for the databases in my instance. Basically I need to move the instance to a new location on the same server due to space limitations of the current directory. All files will be moved to the same new location and the names will remain unchanged. So this is just the path that needs to be changed. (It sounds so simple, it's frustrating that I can't get it to work. :-))

I'm trying to use sp_MSForEachDB

but can't seem to get the correct quotes to pass in the new file location to FILENAME = parameter

commands ALTER DATABASE

.

Here's what I have so far.

DECLARE @command NVARCHAR(1000)--, @filename NVARCHAR(100)

SELECT @command = '
BEGIN
DECLARE @filename nvarchar(100)
USE ?
SELECT @filename = 
    "F:\DevworxExtStorage\Databases\MSSQL12.DEVSQL2014\MSSQL\DATA\" + ? + ".mdf"

ALTER DATABASE ? MODIFY FILE ( NAME = ?, FILENAME = 
"F:\DevworxExtStorage\Databases\MSSQL12.DEVSQL2014\MSSQL\DATA\") 

SELECT @filename = 
"F:\DevworxExtStorage\Databases\MSSQL12.DEVSQL2014\MSSQL\DATA\" + ? + "_log.ldf"
ALTER DATABASE ?_log MODIFY FILE ( NAME = ?, FILENAME = @filename) 


END'

exec sp_MSforeachdb @command

SELECT @command = 'ALTER DATABASE ? SET offline'
exec sp_MSforeachdb @command

      

I get

Msg 102, Level 15, State 1, Line 10 Incorrect syntax near '@filename'.

This is a development database instance, so up and down overflow is not a problem. I would prefer this method over backup / restore as it will be done in seconds, not minutes. We'll also be using this a few times in the future, so it's important to do this script. I know the steps in the script to work when manually released.

I just need help debugging a script, which I think is a problem when using quotes correctly. Thanks in advance for your help!

+3


source to share


1 answer


You need to change the quotes a bit:

DECLARE @command NVARCHAR(1000)--, @filename NVARCHAR(100)

SELECT @command = '
BEGIN
DECLARE @filename nvarchar(256)
USE ?
SELECT @filename = 
    ''F:\DevworxExtStorage\Databases\MSSQL12.DEVSQL2014\MSSQL\DATA\'' + DB_NAME() + ''.md''
END 

SELECT @filename
    '
exec sp_MSforeachdb @command

      



Use single quotation marks for strings and double single quotation marks to avoid single quotation marks.

+1


source







All Articles