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:

osql -Uuser -Ppassword -n -Q "master..sp_detach_db 'database_name'"
scp dburger@something.org:database_name.mdf /cygdrive/f/sqldata
scp dburger@something.org:database_name_log.ldf /cygdrive/f/sqllog
osql -Uuser -Ppassword -n -Q "master..sp_attach_db 'database_name','F:\sqldata\database_name.mdf','F:\sqllog\database_name_log.ldf'"
view raw gistfile1.bat hosted with ❤ by GitHub


Enjoy!