Attaching a Local SQL Server Database Using sqlcmd

Published 18 December 08 02:35 PM

I've been getting asked a lot lately about how to easily attach a local SQL Server/Express database file (.MDF file) to an instance of SQL Server (any edition). In most of my samples I distribute local SQL Server databases and use user instance connection strings so that if you are running Visual Studio with SQL Express then hitting F5 will auto-attach SQL Express to the database when it runs. This will automatically create the log file (.LDF) as well for you. This "just works" approach works well for people who are using the default install of Visual Studio which installs a SQL Express instance.

However, many developers (including myself) have SQL Server developer edition or higher already installed on our machines or connect to remote development machines with higher editions on them. We want to attach the database file to our instance of SQL Server (by the way you can also attach databases to SQL Express). You can do this easily with sqlcmd as outlined in the MSDN library. Here are the steps:

1. First copy the local database MDF file to the same location as your other databases. This is usually the folder: C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data (or if you are using SQL Express it's probably C:\Program Files\Microsoft SQL Server\MSSQL.SQLEXPRESS\MSSQL\Data )

2. Next open a command prompt and connect to your server using sqlcmd using the syntax -S ServerName\InstanceName. You can use the .\ (dot-backslash) syntax to indicate the local server default instance. In the case of SQL Express the instance is called sqlexpress. So to connect to a local SQL Express database:

C:\>sqlcmd -S .\SQLEXPRESS

Or if we were connecting to our local SQL Server default instance:

C:\>sqlcmd -S .\

Or a named instance (SQLInstance) on another machine (RemoeMachine) it would be:

C:\>sqlcmd -S RemoteMachine\SQLInstance

3. Next you need to switch to the master database (<enter> after each line below):

1> USE Master
2> GO

4. Then you need to enter the following command to indicate the new database name to create and the location of the MDF file. This will attach the database and automatically create a new log file for you (<enter> after each line below):

1> CREATE DATABASE databaseName ON
2> (FILENAME= N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\MDFFileName.MDF')
3> FOR ATTACH;
4> GO

Where databaseName is the name of the database and MDFFileName is the physical name of the MDF file. Notice that we're omitting the log file location so it will create one automatically for you. Now you can change your connection strings in your applications to use this attached database in the application settings. For instance many of my samples use a local database called "OMS.MDF". Instead of the user instance connection string:

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\OMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

You can change the connection string in all those samples to:

Data Source=.\SQLEXPRESS;Initial Catalog=OMS;Integrated Security=True

It also becomes a lot easier to modify an attached database from the Visual Studio server explorer or from SQL Server Management Studio. Hope that clears it up for folks.

Enjoy!

Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Tony said on December 18, 2008 7:55 PM:

Beth,

Please why not use sql server?

# No1 Microsoft Fan said on December 18, 2008 8:00 PM:

More goodness from Beth Massi: I've been getting asked a lot lately about how to easily attach a local

# Beth Massi said on December 18, 2008 8:18 PM:

Hi Tony,

What do you mean exactly? MDF files are SQL Server database files. If you are referring to using SQLCmd instead of SSMS then it's because SQLCmd is easier when you don't have the log file (LDF) available.

Cheers,

-B

# Tony said on December 19, 2008 7:04 AM:

Beth I mean sql express, in the real working (telecommunications) is not installed in my company.  Only sql server is installed on our dev servers.  

I think you should target more real world examples.

# Beth Massi said on December 19, 2008 10:07 AM:

Hi Tony,

Umm... that's what this post is all about. SQL Express and SQL Server work the same way when you want to attach database files. SQL Express allows you to have user connections and work with local database files. This post shows you how to take all the samples where I distribute the databases, and instead attach them to your instances -- whether that is sqlexpress or server (I mention "developer edition or higher" in the second paragraph). Sorry I wasn't clear, I updated the wording in the post.

And SQL Express is very real world. It's a great FREE database for small-medium businesses. And upgrading is just a matter of attaching the database to SQL Server like I showed above.

HTH,

-B

# monkey said on December 19, 2008 11:42 AM:

I only find it necessary to move my express db files on Windows Millenium Edition 2008 (aka Vista), otherwise I only use express in website development and attach them in place.

The security and deployment defects of Vista are my #1 complaint about this half baked wad of recursive dough eating dough.

# Beth Massi said on December 19, 2008 12:09 PM:

Hi Monkey,

I'm running as admin on Vista and user instances connect just fine. If you're doing web development then there are some issues when the ASPNET user is auto-attaching to the user instance. If ASPNET does not have write permissions on the database files, the connection fails. (Also see this post for a specific Vista issue with an easy fix: http://blogs.msdn.com/joestagner/archive/2008/03/12/sql-express-failed-generate-a-user-instance.aspx)

However I think attached databases are easier to work with when developing. For attached databases I wrote about how to enable remote connections on Vista here:

http://blogs.msdn.com/bethmassi/archive/2008/09/17/enabling-remote-sql-express-2008-network-connections-on-vista.aspx

I do find Vista to be a little more pesky when developing on it because of it's security model but in general it's been fine with respect to using Visual Studio 2008 and SQL Express.

Cheers,

-B

# monkey said on December 19, 2008 1:45 PM:

My gripe about Windows Millenium Edition 2008: The Sequel has to do with the deployment of application databases and the broken linkage mechanism. This isn't a problem for Cassini website development, but if you try to deploy a windows solution that uses 32 & 64 bit versions of SQL Express, Vista will fail to locate & link your database properly.

It is better the be the balmer than the balmy, apparently the most when they are handing out pay; hence the world economy blue screen.

# Beth Massi said on December 19, 2008 1:58 PM:

Thanks for the feedback Monkey. Though I'm not sure what problem you're running into so it's hard for me to suggest a solution. It sounds like IIS security related to the ASPNET user in which there is a weird fix that requires you to delete the SQLEXPRESS temporary directory.

Do you have a link handy that explains the issue?

TIA,

-B

# monkay said on December 19, 2008 2:43 PM:

Do you know how to change the database name setting in the mdf? Case: copying & renaming a database file to be attached with a new name. This was not previously a problem, either there was no signature or the attach event updated the reference, but now it throws an error.

# Walter said on February 27, 2009 7:49 AM:

Hi Beth - love the videos.

I'm trying to attach the OMS database and I get the error:

"File activation failure. The physical file name "C:\Users\bethma\Documents\Visual Studio 2005\Projects\FormsOverData\OrderManager2\OrderManager\OMS_log.ldf" may be incorrect.

The log cannot be rebuilt when the primary file is read-only.

Msg 1813, Level 16m State 2, Server...

Could not open new database 'BethMassi1OMS'. Create Database is aborted."

I checked the MDF file and it is not read only.

Can you help me with this?

# ahmad@isoftwarehouse.net said on February 27, 2009 9:29 AM:

hallo ....

how add automatic attach database, to sqlexpress in setupdeployment in vb.net

# Beth Massi said on February 27, 2009 12:48 PM:

Hi Walter,

You'll need to make sure the name of the dataabse is OMS.mdf for those samples when you attach it using sqlcmd.

HTH,

-B

# Bill said on March 11, 2009 3:00 PM:

Thanks Beth.

Just what I needed.

Bill

# Abraham zilva said on April 7, 2009 4:59 PM:

how can i attach a file.mdf file from sqlexpress back to visual studio2008. (i attached file.mdf to sql express from visual studio to add the schemas needed for user rolls, but now i can't get it back to visual studio)

# Haroon Shaikh said on April 30, 2009 12:53 PM:

can you please tell me the attaching and detaching of mdf files by sqlcmd in sqlexpress using a batch files

# Paul said on May 28, 2009 8:45 AM:

Beth,

I got this after doing the last "GO"

Msg 948, Level 20, State 1, Server BUG-FUJITSU\SQLEXPRESS, Line 1

The database 'OMS' cannot be opened because it is version 655. This server suppo

rts version 612 and earlier. A downgrade path is not supported.

Msg 1813, Level 16, State 2, Server BUG-FUJITSU\SQLEXPRESS, Line 1

Could not open new database 'OMS'. CREATE DATABASE is aborted.

Please help.

Thank you.

# Beth Massi said on June 2, 2009 11:27 AM:

Hi Paul,

This message means you are trying to attach a SQL 2008 database to a SQL 2005 instance. The version of the OMS database you have must be the 2008 version. You can install SQL 2008 Express for free or you can download the 2005 version of the OMS database from this 2005 sample here:

http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=vbvideosdata&DownloadId=69

HTH,

-B

# Pedro said on October 29, 2009 10:08 AM:

Hello Beth, first of all let me congrat you on your videos... are making my learning a lot less painful...

Now my question is...

I made a SQL database connection on my application... Now I want to deploy it and make it a multi-user dababase... I want to have jsut one instance of the database where all people connect... How can I configure the connection string to match the target computer ? I managed to get SQL to be shared by TCP/IP ... how can i make it install and i dont know pop up a connection menu...that will configure all objects in the database..

Thanks, Pedro

# Beth Massi said on November 4, 2009 1:05 PM:

Hi Pedro,

Once you have the database running on the remote machine you change the connection string in your application to point to the remote database. Make sure you store connections strings in your application Settings (app.config) file and then you can change it without having to recompile the application. If you're using the designers to model your database then they will create a connection sting in the app.config.

For more information :

http://msdn.microsoft.com/en-us/library/a65txexh.aspx

HTH,

-B

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

About Beth Massi

Beth is a Program Manager on the Visual Studio Community Team at Microsoft and is responsible for producing and managing content for business application developers, driving community features and team participation onto MSDN Developer Centers (http://msdn.com), and helping make Visual Studio one of the best developer tools in the world. She also produces regular content on her blog (http://blogs.msdn.com/bethmassi), Channel 9, and a variety of other developer sites and magazines. As a community champion and a long-time member of the Microsoft developer community she also helps with the San Francisco East Bay .NET user group and is a frequent speaker at various software development events. Before Microsoft, she was a Senior Architect at a health care software product company and a Microsoft Solutions Architect MVP. Over the last decade she has worked on distributed applications and frameworks, web and Windows-based applications using Microsoft development tools in a variety of businesses. She loves teaching, hiking, mountain biking, and driving really fast.

This Blog

Syndication

Page view tracker