title: Restore SQL Server database without knowing the Logical File Names
body: <p>I've got a batch file that I use to restore databases. These are <code>.bak</code> files created by other people outside our department, and the database names are predictably unpredictable, as they are usually named for our various customers.</p>
  
  <pre><code>SET servername=XXXXXX
  SET mssqldir=C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL
  SET datapath=%mssqldir%\DATA
  SET dbfile=%~1    
  
  SqlCmd -E -S %servername% -Q "RESTORE DATABASE [MyDatabase] FROM DISK = N'%dbfile%' WITH FILE = 1, MOVE 'Customer' TO N'%datapath%\Customer.mdf', MOVE 'Customer_log' TO '%datapath%\Customer.ldf', NOUNLOAD, STATS = 10"
  </code></pre>
  
  <p>As stated above, the problem with the above command is that <code>Customer</code> is not always <code>Customer</code>.</p>
  
  <p>So when I run it, I get something like:</p>
  
  <blockquote>
    <p>Msg 3234, Level 16, State 2, Server XXXXXX, Line 1<br>
    Logical file 'Customer' is not part of database 'MyDatabase'. Use RESTORE FILELISTONLY to list the logical file names.</p>
    
    <p>Msg 3013, Level 16, State 1, Server XXXXXX, Line 1<br>
    RESTORE DATABASE is terminating abnormally.</p>
  </blockquote>
  
  <p>If I try to restore without the MOVE clauses, the restore tries to put files "back" where they originally came from--like paths that contain other people's home directory:</p>
  
  <blockquote>
    <p>Msg 5133, Level 16, State 1, Server XXXXXX, Line 1<br>
    Directory lookup for the file "C:\TEMP\Not.Me\WidgetsRUs.mdf" failed with the operating system error 2(The system cannot find the file specified.).</p>
  </blockquote>
  
  <p>I'm hoping there is a magic way to basically say: <code>MOVE '*.*' TO '"%datapath%'</code></p>
  
  <p>Any ideas?</p>