Moving TempDB

SQL Server Setup: Moving TempDB

Moving TempDB to another drive or folder is a routine job, but there are a couple of traps. The steps:

  • Identify the Current Location:
SELECT name, physical_name AS CurrentLocation
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
  • Specify the New Location:
USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'new_path\tempdb.mdf');
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'new_path\templog.ldf');

Most servers have several tempdb data files (tempdev, temp2, temp3 and so on), and every one needs moving. This generates the statements for all of them; replace new_path first:

SELECT 'ALTER DATABASE tempdb MODIFY FILE (NAME = ' + QUOTENAME(name)
     + ', FILENAME = N''new_path\'
     + RIGHT(physical_name, CHARINDEX('\', REVERSE(physical_name)) - 1) + ''');'
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
  • Restart SQL Server:
    • Stop the SQL Server service.
    • There’s no need to copy the tempdb files. SQL Server creates them at the new location when it starts. Delete the old files once it’s running.
    • Restart the SQL Server service.
  • Verify the Change:
SELECT name, physical_name AS CurrentLocation
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');

Before moving TempDB: the traps

  • Check the SQL Server service account has full control of the new folder before you restart. If it can’t create the files, SQL Server won’t start.
  • Make sure the new drive has room for every tempdb file at its configured size, because they are recreated at that size on startup.
  • If the service does fail to start, start it with the -f and -mtempdb startup options, point the files back to a valid path and restart normally.

To check tempdb file sizes and usage after the move, see my Health Check 11: tempdb script. For the full reference, see Microsoft’s tempdb database documentation.

From my SQL Server DBA handbook.