Click here to Skip to main content
15,913,685 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,
How can I check if my SQL Server Database is attached to the instance of SQL Server or not. I want to check it at run time and if sa has detached it, I want to show a message. Please give me Vb.Net code if possible.

Thanks
Posted

1 solution

This lists all the connected DBs:
VB
Using con As New SqlConnection(strConnectInstance)
	con.Open()
	Using cmd As New SqlCommand("sp_databases", con)
		cmd.CommandType = CommandType.StoredProcedure
		Dim read As SqlDataReader = cmd.ExecuteReader()
		While read.Read()
			Console.WriteLine(DirectCast(read("DATABASE_NAME"), String))
		End While
	End Using
End Using
If your DB name is in the list, it's attached.
 
Share this answer
 
Comments
Furqan Sehgal 12-Mar-12 4:18am    
I added at the top
Dim strConnectInstance = ".\sqlexpress" and ran your given code but it returns error "Format of the initialization string does not conform to specification starting at index 0." on the Using line
OriginalGriff 12-Mar-12 4:50am    
Try
"Data Source=.\SQLEXPRESS;Integrated Security=True"
or replace the '.' with your server PC name: in my case, I would use
"Data Source=GRIFFPC\SQLEXPRESS;Integrated Security=True"
Furqan Sehgal 12-Mar-12 5:10am    
It resolved that error ! Thanks. I tried to get them in a listbox
using ListView1.Items.Add(DirectCast(read("DATABASE_NAME"), String))
but it did not show anything nor showed any errors.......
OriginalGriff 12-Mar-12 5:32am    
Strange - I just added a ListView and tried it here - I got the list in both the output pane and the listview.
Have you tried putting a breakpoint on the "Dim read as SqlData..." line and stepping through?
As a bare minimum you should get "master", "model", and "msdb" listed as they are present in all SQL server instances.
Furqan Sehgal 12-Mar-12 5:38am    
Really strange ! it did not show either

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