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 "CREATE...FOR ATTACH" stmt. dynamically

By jpcaudill,

In instances where you have over 16 data files, or you need to move data files to a new location when you are moving a database you must use a CREATE...FOR ATTACH statement.  This script will generate the CREATE...FOR ATTACH statement dynamically given a database name.  It will take into consideration the file sizes, growths (automatically determines if it's MB or percentage), filegroups, locations and names.  We've found this quite useful in migrating a VLDB from production to development, which has a completely different drive setup.  Execute this script in the context of master.

Here is an example scenario-

On a weekly basis, you must refresh a development server.  The drive letters are the same on production and development.  In order to accomplish this using this script, you would:

1) Backup your production database.
2) Run this script in the context of master.  Save the SQL statement to a safe place!!!
3) Kill all user processes, and detach your database on production.
4) Kill all user processes, and detach your database on development.
5) Copy the data and log files from production to development.
6) Run the SQL statement generated from step 2 on both production and development.  Your database should be back in normal operating condition.

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

Development and Production Database

Insert Into Development and Production Database at the same time


Production Scripts

Many of us have scripts that we run in SQL Agent jobs, but Steve wonders if we really treat them lik...


Beta Developers Wanted

Mattias Fagerlund, a longtime author and contributor here is developing a new product to help develo...


Simple Maintenance Tasks for Non-Production Databases

Log File Sizes: It's not unusual to see cases where database backups are taken from production and ...


Roles of development DBA

Development Dba vs Production Dba