Generate DB Attach Script in TSQL

Below script will be handy when you migrate databases via detach-attach methord. The script has to be run at the source instance to generate attach scripts including all datafiles and logfiles to be used on the new server.

if OBJECT_ID('tempdb..#filelist') is not null
	drop table #filelist

select db.name as dbName,fs.name as logicalFilename, fs.physical_name as physicalFilename, 0 as done  into #filelist from sys.master_files fs join sys.databases db
on fs.database_id = db.database_id where db.database_id not in (1,2,3,4)


SELECT dbName, Files = STUFF((SELECT N'''), (FILENAME = ''' + physicalFilename
						  FROM #filelist AS p2
						   WHERE p2.dbName = p.dbName 
						   ORDER BY physicalFilename
						   FOR XML PATH(N'')), 1, 3, N'')+''')',
	'create database '+dbName+' on '+ STUFF((SELECT N'''), (FILENAME = ''' + physicalFilename
						  FROM #filelist AS p2
						   WHERE p2.dbName = p.dbName 
						   ORDER BY physicalFilename
						   FOR XML PATH(N'')), 1, 3, N'')+''')'+ ' FOR ATTACH;' AS AttachScript
FROM #filelist AS p
GROUP BY dbName
ORDER BY dbName;

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.