Error - Exclusive access could not be obtained because the database is in use

I am actually trying to make a script (in Sql Server 2008) to restore one database from one backup file. I made the following code and I am getting an error -
Msg 3101, Level 16, State 1, Line 3
Exclusive access could not be obtained because
the database is in use.
Msg 3013, Level 16, State 1, Line 3
RESTORE DATABASE is terminating abnormally.
How do I fix this problem ?
IF DB_ID('AdventureWorksDW') IS NOT NULL
BEGIN
RESTORE DATABASE [AdventureWorksDW]
FILE = N'AdventureWorksDW_Data'
FROM
DISK = N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\Backup\AdventureWorksDW.bak'
WITH FILE = 1,
MOVE N'AdventureWorksDW_Data'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW.mdf',
MOVE N'AdventureWorksDW_Log'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW_0.LDF',
NOUNLOAD, STATS = 10
END

Check, if there are existing connections to the database you are restoring by following command
select spid from sys.sysprocesses where dbid = db_id('AdventureWorksDW')
if you see any existing connections then kill them by issuing KILL command Syntax for kill is
KILL <SPID>
once you see there are no more connections then 
Use mastergoIF DB_ID('AdventureWorksDW') IS NOT NULL
BEGIN
RESTORE DATABASE [AdventureWorksDW]
FILE = N'AdventureWorksDW_Data'
FROM
DISK = N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\Backup\AdventureWorksDW.bak'
WITH FILE = 1,
MOVE N'AdventureWorksDW_Data'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW.mdf',
MOVE N'AdventureWorksDW_Log'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW_0.LDF',
NOUNLOAD, STATS = 10
END
Mark as answer, if it works.

Similar Messages

  • Exclusive access could not be obtained because the database is in use

    Hi
    I am trying to use sql server 2005 management stodio to restore a database. But I got this error message:
    Exclusive access could not be obtained because the database is in use
    Anyone know how to solve this problem?
    Thanks
    Li

     Li556035 wrote:
    Hi
    I am trying to use sql server 2005 management stodio to restore a database. But I got this error message:
    Exclusive access could not be obtained because the database is in use
    Anyone know how to solve this problem?
    Thanks
    Li
    If you don not have any process running on your pc that uses your database like Enterprise Manager or any other third party application, use
    SqlConnection.ClearAllPools();
     in C# code before restoring. Like the following code:
    Code Snippet
    public void BackupAndRestore(string Query)
         SqlConnection.ClearAllPools();
    SqlConnection connection = new     SqlConnection(ConfigurationManager.AppSettings["ConnectToMasterDB"]);
         SqlDataAdapter da = new SqlDataAdapter();
         da.SelectCommand = new SqlCommand();
         da.SelectCommand.Connection = connection;
         da.SelectCommand.CommandText = Query;
         da.SelectCommand.ExecuteNonQuery();

  • Search Error: This item could not be crawled because the crawler could not connect to the repository.

    Our Search Service got hosed after install of SP1/June CU (didn't upgrade), so I re-created it, but when setting up rules, content sources, I am getting the following error:
    This item could not be crawled because the crawler could not connect to the repository.  I tried crawling using admin account, so I don't think it is permission related.  The DisableLoopbackCheck in the registry is already set...
    We previosly had crawl working on this farm, so shouldn't be because we are using host headers and the loopback issue.  Does anybody have any ideas?  Another error that may be related...
    SharePoint Web Services Round Robin Service Load Balancer Event: EndpointFailure
    Process Name: OWSTIMER
    Process ID: 1612
    AppDomain Name: DefaultDomain
    AppDomain ID: 1
    Service Application Uri: urn:schemas-microsoft-com:sharepoint:service:edd515218442481abce89e54e3c63a64#authority=urn:uuid:a297b0fb965f465ca42051f55fa3f4bd&authority=https://spapp-wc-2p:32844/Topology/topology.svc
    Active Endpoints: 4
    Failed Endpoints:3
    Affected Endpoint:
    http://[ourservername]:32843/edd515218442481abce89e54e3c63a64/ProfileService.svc
    Any suggestions are appreciatted, this is a tricky one...
    Jonathan Herschel

    Make sure your hosts file on each server in your farm has 127.0.0.1  webappname in it for each SPSite you're trying to crawl
    Look in %systemroot%\system32\drivers\etc and edit the hosts file so that it has entry for web app
    make sure search account listed as access account is also service admin for search service
    check user policy on web app, make sure that account has full read
    Check that SharePoint Web Services Root app pool is started on server that is indexing farm
    if still cant crawl, give search account db_owner on content db using sql server management studio
    Set BackConnectionHostNames for site collection.
    Then in a non prod environment, reset index and perform a full crawl, repeat in prod.
    Stacy Anothersharepointblog.blogspot.com

  • HT201407 I have a new device. When selecting the language and country I am trying to connect to a wifi connection and getting the error 'Your Iphone could not be activated because the activation server cannot be reached. Try connecting to your Iphone to i

    I have a new device. When selecting the language and country I am trying to connect to a wifi connection and getting the error 'Your Iphone could not be activated because the activation server cannot be reached. Try connecting to your Iphone to iTunes to activate it, or try again in a few minutes.

    Where exactly did you get this phone?
    Do you have a SIM in the phone?
    There are 2 primary causes for this.
    Either you don't have a SIM in the phone, which is REQUIRED to activate it, or the phone was hacked to unlock it.

  • Error: Page Metadata could not be obtained from the Portal database.

    Hi,
    Maybe some one can help me with this.
    After my installation (oas portal 10.1.4) I changed my URL in portal and sso.
    modplsql : http://<webserver>:<port>/pls/portal/htp.p?cbuf=test --> its working fine. I got test
    Parallel Page Engine (PPE) : http://<webserver>:<port>/portal/page --> its working fine. I got PPE is working.
    http://login.hostname:port/oiddas --> It`s working fine
    http://login.hostname:port/sso --> It`s working fine
    http://hostname:port/portal/page/portal/TOPLEVELSITE --> It's not working I got in firefox Error: Page Metadata could not be obtained from the Portal database. In explorer i got HTTP 500 error.
    I checked my application.log and I got this:
    **portal: id=45342345678,1 ContentFetcher Unexpected Exception Request Failed:oracle.webdb.dispatcher.DispatcherException: I/O Error dispatching request name=content-fetcher19 label=pageMeta url=http://<webserver>:port/portal/pls/portal/!PORTAL.wwpob_page.show/TOPLEVELSITE time=1ms timeout=60000ms process=Dispatching**
    Maybe some one can help me to solve this threat.
    Thank you.

    C@rlitos wrote:Edited by: C@rlitos on Sep 30, 2009 6:14 PM
    Hi!!
    To register the url in portal I used this doc 434795.1 - 558634.1 from metalink.
    http://download-west.oracle.com/docs/cd/B14099_17/core.1012/b13998/variants.htm#CBDBDJHD
    I verified and i got this:
    LSNR_TOKEN
    SITE_TOKEN
    SITE_ID
    LS_LOGIN_URL
    URLCOOKIE_VERSION
    ENCRYPTION_KEY
    ENCRYPTION_MASK_PRE
    ENCRYPTION_MASK_POST
    U
    oldurl.com:7781
    XY776FQWDCY4EFF
    8AC54EFF
    http://oldurl.com:7780/pls/orasso/orasso.wwsso_app_admin.ls_login
    v1.2
    2FWERFW768767866
    6B4DEERWF87W87897E89WRF897W3FC9
    F0FEC6AREW76786WEFWER76F8968695
    N
    newurl.com
    1RG8IYA4F9D2E30A
    F9D2E233A
    http://newurl.com/pls/orasso/orasso.wwsso_app_admin.ls_login
    v1.2
    B32852345661513F0
    1A5DTR546EYEYEHEHSVSGFB44C
    A33RTWERGERGERGREFWERF8
    N
    I havent create new token values.
    Edited by: C@rlitos on Sep 30, 2009 6:14 PMHave you configured your Infra with a new hostname on a different port ?
    Unless, you had installed your OAS with custom ports, and have not used the default ports for the components, your lsnr_token for the newurl has a problem. orasso and sso should be configured at 7777, and by default they configure at that port. That means that your newURL should be pointing to http://newurl.com:7777/pls/orasso/orasso.wwsso_app_admin.ls_login for the ls_login_url.
    This might have happened due to some error in registering your portal with the SSO. Have you used custom ports for your installations?
    Additionally, did you configure your newurl on port 80?

  • TS3694 what to do when the error message says could not be restored because the firmware file is not compatible

    what to do when a error message says could not be restored because the firmware file is not compatible

    Were you updating/restrore via the Restore/update button in iTunes?
    Try deleting the existing ufirware file and try again
    It is located here:
    IPSW file location for Mac and Windows

  • 2 errors: "Your iPhone could not be activated because the activation server is temporarily unavailable" and the sim says "searching" while iTunes says there is "No Sim installed" - but of course, there is! Any help please??

    2 errors: "Your iPhone could not be activated because the activation server is temporarily unavailable" and the sim says "searching" while iTunes says there is "No Sim installed" - but of course, there is! Any help please??

    Hi Peter,
    Thank you for the note - I have seen similar replies on other posting errors and I see how that could make sense. The thing is, my iPhone is not jailbroken - it is from an authorized distributor. However, when I told them about the "no service" problem on the sim, they were unable to assist. Then my phone messaged that an itunes restore was required - so I did that, several times, to the error message now noted on my post. I wonder if there is some other way to over-write this message? Thanks very much.

  • Win8 Pro Hyper-V Error : Virtual machine could not be started because the hypervisor is not running

    Hello,
    Recently in Dec I bought a new desktop PC.
    HP ENVY Desktop h8-1420t
    CPU & ChipSet:   Intel Core i7    Intel Z75
    I have Windows 8 Pro and installed Hyper V but cannot start the virtual machines. I get the following error message: Virtual machine 'zzzz' could not be started because the hypervisor is not running
    I followed these steps to enable Hyper-V:
    1. Upgraded to Windows 8 Pro
    2. Tried to add Hyper-V feature but Hyper-V Platform was grayed out
    3. Enabled Virtualization in the BIOS - security configuarion
    4. Cold booted Computer
    5. Added the Hyper-V Platform Feature
    6. During the restart machine was in forever state spinnign state, did a manual reboot
    7. Disabled Virtualization in the BIOS again
    8. Successfully Re-Booted the Computer now Hyper V manager was available
    9. Configured Hyper V network to use external network
    10. Created a new VM through the Hyper-V Manager
    12. Tried to boot up teh newly Created VM and I get this error message:
    Virtual machine 'zzzz' could not be started because the hypervisor is not running
    Any solutions for the error I am seeing above?
    Similar problems are discussed here:
    http://h30434.www3.hp.com/t5/Desktop-Lockups-Freezes-Hangs/Cannot-boot-if-HP-ENVY-Bios-Virtualizatio...
    Thanks!!

    Same Problem Here - did you discover any answers?  I may have to return the system if it can't do hyper-v

  • While trying to activate 3GS , get error "your iPhone could not be activated because the activation server is temporrarily unavailable. When will ther server be available? is anyone else experiencing this problem?

    While trying to activate iphone 3gs  get an error message saying " your iphone could not be activated because the activation server is temporarily unavailable" when will they be available, and is anyone else having this problem?

    yes i am! did u get it fixed?

  • I get this message when trying to open a file from my company cloud: Error: This action could not be taken because the applet has not initialized. What do I need to do to be able to look at a file? Thank you!

    Help!

    There is software you installed to work with your company's cloud service, update it or talk to the developer.
    If it's Apple's software,  then run through this list of fixes.
    ..Step by Step to fix your Mac

  • Could not be saved because the source file could not be read.

    I tried to download and after a while, this error message: ''[filename] could not be saved because the source file could not be read.'' I've been on google searching but I could not find the answer can someone PLEASE help me. it happened when downloading a game and I've already seen a few times before but it was less important.
    sorry for the bad english I used a translator.

    This problem isn't only happening with Firefox 4, for windows, as the System Details, and Tags indicate.
    I'm using a Mac laptop (OS X 10.5.8 -- Leopard), using Firefox 6, and have been having this problem with large files for quite a while ... possibly since FF 4, but definitely with FF 5. The large files I've had the problem with are in the 500 - 900 MB range, and from commercial sites as well as most recently with a zip file containing photos from a friend which he uploaded to dl.dropbox.com ... attempted it numerous times, after trying the various suggested "fixes", and each time at around 255 MB, the download quits, with the error that file cannot be read from the server.
    The various proposed solutions I've found on the web -- resetting the user configured options connected to downloads in FF config (about:config); deleting the compreg.dat file in the FF profile folder, don't pause the download (never have done this) etc.
    Others have opined that the problem is flaky intermittent WiFi, or Security/Anti Virus software interfering with FF's accessibility to the file during the download; or a caching problem at one's ISP -- HOWEVER Safari doesn't experience this problem at all. Each time that I've experienced it in FF, I launch Safari, and can download the file completely without any errors.
    Would really like to see someone from Mozilla respond to this ... lots of us are experiencing it.
    Whatever happened to Netscape's ability to recover from download interruptions and resume a download at the point where it had been interrupted (like when a dial up modem dropped the line in the middle of the download) -- sure would be useful to see that feature come back in FF.
    Thanks,
    Muiz

  • ITunes could not copy ''file'' because the file could not be written

    Recently, I have been experiencing some problems with iTunes and my iPad 2. Whenever I try to sync movies into my iPad, I get the error message ''iTunes could not copy ''file'' because the file could not be written''. This message always appears whenever I try to sync a few movies at once. When I check my iPad after it's synced, I find that a few of my movies successfully sync into my iPad, and can be played. However, some movies show up on my iPad but cannot be played. The video thumbnail just shows a picture of a blank TV screen. Is there any way where I can fix this problem? Thanks.

    Hi JimmySlax.
    I was having the same issue with music and movies but it had been ok before. The sync would freeze on a random file and then i had to take out the USB cable to clear it. After trying all sorts of things i saw someone mentioning about Anti virus and firewalls. I am using McAfee so i disabled it as a test. After this i could sync music and movies without issue!!!!! So in my case the firewall/anti virus was causing a problem. McAfee updates itself a lot so I am guessing something has happened in a recent update that impacted iTunes.I am not sure if this kind of thing is also causing your problem but it sounds very familiar.
    Hope this helps.

  • CS2/W8 - Could not initialize photoshop because the file is locked

    I just upgraded to Windows 8 64 bit last night.  I had been running Cs2 just fine on Windows 7 64 bit for a few years now.   In fact I used it last week.  Now after the upgrade is complete, I get this error message when I try to launch CS2: 
    Could not initialize photoshop because the file is locked. use the properties command in the Windows Explorer to unlock the file.
    Of course, there is no mention of which file is locked. 
    I tried a repair install, it didnt help, same error. 

    HAve you tried resetting preferences?  Start PS and IMMEDIATELY hold down the shift ctrl alt keys.  Should get a reset window if fast enough.

  • Itunes isn't letting me sync.  It is saying it could not be synced because the sync session failed to start.  Happening on all our devices.

    When trying to sync my devices, I'm getting an error saying it could not be synced because the sync session failed to start.

    Restart your computer.

  • IPad could not be restored because the firmware file is not compatible.

    Hi, i have the latest 3rd gen iPad 32GB and iTunes 10.6. I have the IOS 6 beta downloaded on my windows laptop. I had someone add my UDID to there apple developers acount. However when i press Shift+Restore and select the beta file a i get an error sayng 'iPad could not be restored because the firmware file is not compatible.' Has anybody got any idea on how to restore my iPad to the IOS 6 beta file i have downloaded?
    Thanks in advanced
    Joseph.

    You should ask this question in the Apple Developer Forums
    Since iOS 6 is not officially released nobody else can help.

Maybe you are looking for

  • How to structure a multiple business WM solution in SAP

    Hi there, I am in a preparation phase to show our business the merits of SAP WM, replacing a third party system. As I'm new to WM I'm struggling a bit with the possible structures to use for our DC. I understand the SAP and standard WM structures how

  • Tiger to Leopard transition- user name and password not working. plz help!

    Hi all. Last year I purchased a MacBook Pro with Tiger OSX. Anyways I wanted to switch to leopard, so I did. Now when I want to install updates, as usual it requires my user name and password. But after I installed leopard, my old user name and passw

  • Information about currently active calls

    Hi, We have a Cisco3845 router that acts as a VoIP gateway that is, it converts TDM traffic from the Public Switched Telephone Network (PSTN) into H.323 traffic. My problem is that we would like to know how many calls are going through the gateway an

  • FRM-92150 Fatal error web client version is too new

    Need help!! OS 2008 64 bit 1.     Installed Weblogic server 10.3.5 2.     Installed Forms and reports ONLY 11.1.2 3.     Configured --> everything worked We have a need to run a Discoverer 11G a well. Since Discoverer was not part of original Forms a

  • AIR Badge - Publisher ID Problem?

    In order to check if an AIR application is installed (using the ProductManager class) I have to use the publisher ID contained in the application's "META-INF/AIR/publisherid" file, not the publisher ID defined in the code signing certificate used to