USE [DBName] fails if DB created just before calling it

(SQL 2005)

I'm obviously missing something simple: why doesn't this work

USE MASTER;

if exists(select name from sys.databases where name='MLMS') DROP DATABASE [MLMS];

CREATE DATABASE [MLMS];

USE MASTER;

-- misc cmds

USE [MLMS];

This works if MLMS exists, but fails if it doesn't.  In that case, syntax checking returns an error indicating MLMS doesn't exist:

Msg 911, Level 16, State 1, Line 7

Could not locate entry in sysdatabases for database 'MLMS'. No entry found with that name. Make sure that the name is entered correctly.

Thanks in advance.



Answer this question

USE [DBName] fails if DB created just before calling it

  • EricV

    if you are using SQL Management Studio, or Query Analyzer, put a GO between the drop and create, and the create and use.

    This will force it to execute the statements as separate commands.

    BobP



  • kpraveen

    Unfortunately, that is what I tried before and it doesn't work (though I am surprised that the compilation requires the DB to exist - I would have expected that to be a runtime error).  

    In any case, I have come to suspect problems with my system.  So I'm going to try rebuilding it and hope the problem goes away.  Thanks for your help.


  • DREAM_G

    The error is thrown at compilation time because of the USE [MLMS] statement. Put a GO before the USE [MLMS] statement which will split the above batch into two and it will work fine.

  • Anonymous1234afv34

    Unfortunately, that didn't work. Even a GO after each line didn't work. BUT....if I manually execute one line at a time, it does work.
  • USE [DBName] fails if DB created just before calling it