views:

284

answers:

2

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?

+4  A: 

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.

David M
+2  A: 

Thanks to your hints I've found the solution:

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

USE [MY_DBNAME]
GO
AOI Karasu