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;
Technology enthusiast Sherbaz is a Microsoft certified SQL Server Subject Matter Expert. He had fun automating day to day task to achieve management goals. He has extensive hands-on experience in high availability deployments and support with several years of industry experience performing SQL Server installations, configuration, maintenance, backups, performance tuning, Transactional & P2P replication, migration, high availability solutions (Always on, Failover Clustering, Logshipping and Mirroring) and Disaster recovery.
Sherbaz also has basic hands-on experience in other DBMSs like MongoDB, Oracle 9i, 10g, Sybase and MySQL. 1 year on Mongodb, Oracle 9i & 10g. Completed M102 & M202 courses in MongoDB.
Sherbaz spends his spare time with automation in electronics, embedded system circuits and IOT in his private lab at home.
Also, he supports his customers and users at www.SplitExpense.in for issues with app, website or telegram chat bot @SplitExpenseBot https://t.me/SplitExpenseBot. @TheSherBot https://t.me/TheSherBot is another telegram chat bot, partially artificial intelligent, programmed and maintained by him on python and backend Mongodb database.
Sherbaz always showed interest learning new technologies and to think out of the box bringing innovation in work. Some of his work is documented @ www.sherbaz.com.
He is now busy learning 3D modeling software on his roadmap towards building his next hobby build, A 3D PRINTER.
Subscribe to his youtube channel
https://www.youtube.com/c/SherbazMohamed/
View all posts by Sherbaz