Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am newbie to SQL Server Express. At the moment I am manually attaching the DBs using SSMS but I need to do it through code.
I have searched a lot over internet but could not really start anything.

I know there is a sp_attach procedure but donot know how to use it and then how to call that through my application's setup. How to use SQLDMO

Could any help be given to me please?

Thanks
Posted

Do not use sp_attach_db(). As MSDN states it may be removed in the future.
Use CREATE DATABASE .... FOR ATTACH

SQL
CREATE DATABASE [C:\xyz.MDF] ON
( FILENAME = N'C:\xyz.mdf' ),
( FILENAME = N'C:\xyz_log.LDF' )
 FOR ATTACH


If you're using SSMS, before hitting the 'OK' button, check for the Script button on top. Click it & it'll show you the underlying script for the action. You can learn from it.
 
Share this answer
 
Comments
Furqan Sehgal 4-Feb-12 11:15am    
But I donot know where to write the above code and then how to call it in my vb.net application.
strogg 5-Feb-12 3:51am    
Here's one way to do it in vb.net

Dim con As New SqlConnection("Your connection string")
con.Open()
Dim cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "Your statement to execute"
cmd.ExecuteNonQuery()
con.Close()
You need to import System.Data.SqlClient.
If you do not know anything, this is not the way to learn. Read some concerned book or go through the MSDN and learn before you use.
Depending on your needs, another option to attaching the database by creating it is to attach the database file during the connection using AttachDbFilename parameter.

This is commonly used for example if the SQL Server installation is local and for one user. See: http://www.connectionstrings.com/sql-server-2008[^]
 
Share this answer
 
Comments
Furqan Sehgal 4-Feb-12 11:16am    
But just giving it in connection string does not attach it to the SQL Server instance
Wendelius 4-Feb-12 11:22am    
That's one way of attaching the database, see Connecting to SQL Server Express User Instances (ADO.NET)[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900