Link to home
Start Free TrialLog in
Avatar of indy500fan
indy500fan

asked on

Trying to Set a SQL Server Database to Offline through VB.NET

Friends,

I'm having a bit of trouble trying to set a database to offline through VB.net

If I simply type the lines:

 ALTER DATABASE  [IRLRV]
SET OFFLINE

through Query Analyser, it works great.  If however, I write it in my code such as the case in the attahed code snippet, i get a timeout error?  What gives?

It should be noted that if I try to run the same line from Qry Analyser while my program is running, it will sit there and think about it until I have closed my program.  After the program exits, it will then run in qry analyser.

 What syntax change to I need to make?

Thanks in advance!

Regards,
Eric


dsnLocal = "Data Source=""" & LocalWorkstation & """;Initial Catalog=""master"";User Id=""user"";password=""password"""
   
Private Sub SetDatabaseToOffline(ByVal NewDBName As String)
        Dim con As New SqlClient.SqlConnection(dsnLocal)
        Try
            Dim data As New DataSet
            data = New DataSet
            con = New SqlClient.SqlConnection(dsnLocal)
            con.Open()
 
            Dim c As New SqlClient.SqlCommand("ALTER DATABASE [" & NewDBName & "]" & vbCrLf _
            & "SET OFFLINE", con)
            c.ExecuteNonQuery()
 
            con.Close()
            con = Nothing
 
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
 
        Finally
            If Not con Is Nothing AndAlso con.State <> ConnectionState.Closed Then
                con.Close()
                con = Nothing
            End If
        End Try
    End Sub

Open in new window

Avatar of brejk
brejk
Flag of Poland image

Try to execute it with some additional option:

ALTER DATABASE  [IRLRV]
SET OFFLINE WITH ROLLBACK IMMEDIATE
Avatar of Chris Mangus
You're probably trying to set it offline while your app is connected to it.  Try connecting to another database first in your app, like maybe tempdb, then set IRLRV offline.
Avatar of indy500fan
indy500fan

ASKER

cmangus, If you look at my connection string, I am connected to master.  That is what is so confusing.

brejk, what does ROLLBACK IMMEDIATE do?
ASKER CERTIFIED SOLUTION
Avatar of Chris Mangus
Chris Mangus
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
cmangus,

Yep, I did infact have one user connected.  I changed all my connection strings in the routine to use the masterdb, and it worked!

Thanks,
Eric