Wednesday, September 24, 2008

Attach and Detach SQL Server Databases from the Command Line with osql

I'm usually working with MySQL but I also work on a project that uses SQL Server for a back end. Lately I've been writing a script that massages some data from a CSV dump from another system into our system. This led to a rather, rinse, repeat cycle of switching to SQL Server in VMWare, detaching the existing database, copying a fresh copy of the database into place, and re-attaching the data when doing sample runs of the script against the data. This got to be a real hassle! Finally I took the time to learn how to detach and attach a SQL Server database using command line osql commands. Here is an example of a script that detaches the database, copies clean files into position, and then re-attaches the database:



Enjoy!