Q
Problem solve Get help with specific problems with your technologies, process and projects.

Error with RESTORE DATABASE in vb.net code

I am trying to perform a RESTORE DATABASE operation, using T-SQL in a vb.net project on the current SQL database connection. Below are two code snippets I am working with:

1.

cn.open() 'current connection
Dim comSQL As New SqlClient.SqlCommand
comSQL.Connection = cn

comSQL.CommandText = "RESTORE DATABASE 
  
    FROM DISK = '
   
    ' WITH REPLACE, NORECOVERY, PASSWORD = '
    
     '"

comSQL.ExecuteNonQuery()
cn.close()

    
   
  

2. Same as above, except I use the SQLDataAdapter, SQLDataReader to execute the RESTORE clause.

In both cases, the operation fails and the error message 'excusive access could not be obtained because the database is in use' is generated. The current database connection is only used as a placeholder for user databases that are brought into the application for data editing and reporting, so the current database info is disposable. How can I perform this restore operation in code?

Change your database context to master. You will also have to kill off any SPID that is connected to the database you are trying to restore. Refer to the kill command in BOL.

For More Information

This was last published in June 2004

Dig Deeper on SQL-Transact SQL (T-SQL)

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close