SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Generate script to tidy up DB Logical File Names

By Neil Jacobson,

You may be a tidy person who likes to keep naming standards for everything in SQL Server.  It is a good practice since it makes generating scripts for everyday DBA tasks a lot simpler.  I make all database files follow the following standard:
DBName_D1.mdf     for primary filegroup data
DBName_I1.ndf     for index filegroup
DBName_L1.ldf     for transaction log file

The number increments for subsequent files.  The logical filenames are used by lots of things such as RESTORE DATABASE WITH MOVE.

If you run Select name, filename from master..sysaltfiles you can see the state of your filenames at a glance. I'm not concerned with the system files but I am very consistent with user databases.

Change the operating system file is as simple as detach db, rename file, reattach using new names.

Changing the Logical File Name requires an ALTER DATABASE statement.  I don't like repetitive typing so I just run the following stored procedure from the target database to generate the statement for me.

DECLARE @RC int, @xDBName varchar(85)
-- Set parameter values
Select @xDBNAme = DB_Name()
EXEC @RC = [dbo].[sp_AlterLogicalNames] @xDBNAme

Total article views: 247 | Views in the last 30 days: 1
Related Articles

Use Database table to dynamically get the excel filename

Dynamic excel filename and path from database table


Retrieve Part of the Filename stored in a variable

Retrieve FileName from a variable


understand following concepts of resouce database:

understand following concepts of resouce database:


Problem Using a Dynamic Filename for a Database Restore

Trying to use T-SQL to restore a database from a backup with a changing date in the filename


filename management

retrieving filenames from directory and store it into a SQL database