title: Programmatically detach SQL Server database to copy mdf file
body: <p>I have a small SQL Server database that I need to copy on command -- I need to be able to take the mfd and ldf files at any given moment, copy them, zip them, and make them available to an end user.</p>
  
  <p>Right now this is possible by manually:</p>
  
  <p>1) Logging onto the SQL server via Remote Desktop</p>
  
  <p>2) Detaching the database via SQL Management Studio. I have to fiddle around with a combination of setting the database to single_user and/or restarting the service so I can get it to detach since the app server is normally logged into it.</p>
  
  <p>3) While detached I go through the file system and copy the mdf and ldf files.</p>
  
  <p>4) I re-attach the database via SQL Management Studio</p>
  
  <p>5) I zip the copied files, and I move them to an FTP server so the people who need them can get them.</p>
  
  <p>It's a horrible, inefficient process. It's not just a matter of needing the schema, but rather a need for people to work with snapshots of real, production data on their own local machines for the purpose of destructive experimentation. Luckily the zipped database is very small -- maybe 30 megs with the log.</p>
  
  <p>So ideally, I'd like to create a page in the ASP .NET web application that has a button the user can press to initiate the packaging of the current database into a zip file, and then I'd just provide the link to the file download.</p>