Search code examples
sql-serverselectsql-server-2000existssysdatabases

MS SQL Server 2000 - check for existing database error


I use MS SQL Server 2000 SP4 and I have this part of script, that checks for existing database:

IF EXISTS (SELECT * FROM sysdatabases WHERE name='MY_DBNAME')
BEGIN
    PRINT 'Using the existing database MY_DBNAME.'
    USE MY_DBNAME
END
ELSE
BEGIN
    PRINT 'Creating new database MY_DBNAME.'
    CREATE DATABASE MY_DBNAME
END
GO

I keep getting this error:

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

Is there a way to disable this message, or is there another way for checking, if a table exists?


Solution

  • It's trying to compile the whole thing, including "USE MY_DBNAME" before it runs. Compilation fails because this database doesn't exist. You can't, I'm afraid, do what you're trying to do in a single SQL batch.