Search code examples
sqlsql-server-expressmdf

Running sql scripts against an attached database?


I've got an MDF attached to an instance of Sql Server 2008 Express, and I need to run some sql scripts against it to generate tables, indexes, etc.

But I can't figure out how to get this to work. If I load the scripts in Visual Studio, it only allows me to connect to the server and run it against a database. I can't choose a different provider (Microsoft Sql Server Database File), so I can't select my MDF.

This leaves me the only option of running the script as individual queries, but that won't work as it appears it doesn't support TSQL CREATE statements.

How can I run my sql script against an attached database?


Solution

  • I ran into this same problem and here is what worked for me.

    1. Right-click on the script and choose Connection > Connect

    2. The server name and authentication should already be set for the local SQLEXPRESS instance.

    3. Click the Options button

    4. Click the Additional Connection Parameters tab

    5. Paste in the the path to your database file using the following as a guide:

      AttachDBFilename=C:\Path\To\Database\LocalData.mdf;database=LocalData;

    6. Click the Connect button

    If you still have trouble connecting it may be because there is already an open connection. Check Server Explorer and if connection is open, Right-click and choose Close Connection.

    This process will also create a persistent connection as long as the SQL Script remains connected. You will want to close the script or choose Right-click > Connection > Disconnect.

    More information can be found at this question: EF4 Generate Database