Question

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?

Was it helpful?

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top