Technical Article

Build a script for CREATE DATABASE/FOR ATTACH

,

It is easy enough to detach and reattach databases in SQL 2000 providing you have less than 16 files to attach.

I manage some very large databases and these sometimes need to be detached and reattached (i.e. for moving a database file from one volume to another).

I have more than 16 files to contend with on these monsters.  Since I hate repetitive typing, I use this script to generate the CREATE DATABASE FOR ATTACH statements for all our databases.

To use it, run it then take the results and run the results. Repeat with those results. The last set of results are the Create Database For Attach statements.

It is good for any number of files.

use master
go
Set nocount on

Select 'Use ' + name + char(10) + 'go' + char(10) + 'Set nocount on' + Char(10) + 
'Select ''CREATE DATABASE '' + Rtrim(db_name()) + '' ON'' from master.dbo.sysdatabases where name = Rtrim(db_name())'
+ char(10) + 'Set nocount on' + Char(10) + 'select ''     (FILENAME = '''''' + rtrim(filename) + '''''')'' from sysfiles Where fileid = 1 ' 
+ char(10) + 'Set nocount on' + Char(10) + 'select ''   , (FILENAME = '''''' + rtrim(filename) + '''''')'' from sysfiles Where fileid <> 1 order by fileid' 
+ char(10) + 'Set nocount on' + Char(10) + 'Select ''FOR ATTACH''' + Char(10) + 'Set nocount on' + Char(10) +
'Select ''go'''
+ char(10) + 'go'
  from sysdatabases 
where NOT(name IN ('master','tempdb','model','msdb'))
Order by name

Rate

4.67 (3)

You rated this post out of 5. Change rating

Share

Share

Rate

4.67 (3)

You rated this post out of 5. Change rating