At this time I'd like to share some scripts that used undocumented (sorry) but very popular among DBA's sp_MSforeachdb stored procedure. If you have hundred of databases on your server and you was told to move those databases to another server the quick way to do the job is performing the following scripts. First of all we detach all user databases from the server and the second query will output an attach
script. The thing is that the second query will output the script that attach the database that has more than one LOG file.
I'm sure that you have backuped the user databases before performing such tasks.
--Detaching
EXEC sp_MSforeachdb
'IF N''?'' NOT IN(''model'' ,''master'', ''msdb'', ''tempdb'')
BEGIN
SELECT ''EXEC sp_detach_db ''''?'''',''''true''''''
END'
--Attaching
EXEC sp_msforeachdb
'SELECT ''EXEC sp_attach_db ''''?'''',
'''''' + RTRIM(filename) + '''''',''
FROM ?..sysfiles
WHERE fileid = (SELECT MIN(fileid) FROM ?..sysfiles)
UNION ALL
SELECT '''''''' + RTRIM(filename) + ''''''''
FROM ?..sysfiles
WHERE fileid > (SELECT MIN(fileid) FROM ?..sysfiles) AND
fileid < (SELECT MAX(fileid) FROM ?..sysfiles)
UNION ALL
SELECT '''''''' + RTRIM(filename) + ''''''''
FROM ?..sysfiles
WHERE fileid = (SELECT MAX(fileid) FROM ?..sysfiles)'
Wednesday, March 21, 2007
Subscribe to:
Post Comments (Atom)
2 comments:
Uri:
Great scripts, but have run into an issue. The script to create trhe DETACH statements works fine, However, the script to generate the ATTACH statements fails on certain databases.
The databases it fails on are any database that has the character "&" in the name.
Can you provide a workaround/solution for this?
Thank you!
Post a Comment