title: SQL Server recovering database after relocating files
body: <p>I wrote a tool to move a lot of database files to a different partition. These databases are using SIMPLE recovery and don't get changed much, so I thought something like this would do:</p>
  <pre><code>// this is a mix of sql commands and disk copy commands
  
  // single user, then offline
  SQL: ALTER DATABASE [MY_DATABASE] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
  SQL: ALTER DATABASE [MY_DATABASE] SET OFFLINE WITH ROLLBACK IMMEDIATE
  
  // copy to target folder
  COPY &quot;SOURCE\MY_DATABASE.mdf&quot; &quot;TARGET\MY_DATABASE.mdf&quot;
  COPY &quot;SOURCE\MY_DATABASE_LOG.ldf&quot; &quot;TARGET\MY_DATABASE_LOG.mdf&quot;
  
  // delete from source folder
  DELETE &quot;SOURCE\MY_DATABASE.mdf&quot;
  DELETE &quot;SOURCE\MY_DATABASE_LOG.ldf&quot;
  
  // modify
  SQL: ALTER DATABASE [MY_DATABASE] MODIFY FILE (name = 'MY_DATABASE',
      filename = 'TARGET\MY_DATABASE.mdf');
  SQL: ALTER DATABASE [MY_DATABASE] MODIFY FILE (name = 'MY_DATABASE_LOG',
      filename = 'TARGET\MY_DATABASE_LOG.ldf');
  
  // multi user, then online
  SQL: ALTER DATABASE [MY_DATABASE] SET MULTI_USER WITH ROLLBACK IMMEDIATE
  SQL: ALTER DATABASE [MY_DATABASE] SET ONLINE
  </code></pre>
  <p>However, the last operation (<code>SET ONLINE</code>) often hangs and waits some time, and when I query <code>master.sys.databases</code> I can see that the state is <code>RECOVERING</code>.</p>
  <p>Can somebody explain why this is happening, what am I doing wrong here, or if I should do the whole thing in a different way?</p>