I am working on project with multiple databases. There is a chance the database may not exists. I am checking to see if the database exists before I run query against the table. The issue is that I am still getting database "Courses" does not exit. I'd like to get rid of that message because I don't want the client to see this message.
DECLARE @dbname nvarchar(128)
SET @dbname = N'Courses'
IF EXISTS (SELECT name
FROM master.dbo.sysdatabases
WHERE ('[' + name + ']' = @dbname
OR name = @dbname))
BEGIN
IF NOT EXISTS (SELECT 1 FROM Courses.INFORMATION_SCHEMA.COLUMNS C WHERE C.COLUMN_NAME IN ('isAvailableOnline') AND C.TABLE_NAME IN ('Course'))
BEGIN
ALTER TABLE Courses.dbo.Course ADD isAvailableOnline BIT NULL
END
END
'[' + name + ']'you ought to be usingQuoteNameto quote an object name.dbo.sysdatabaseswill be stored unquoted. Anddbo.sysdatabasesis deprecated (replaced bysys.databaseswhere it will also be unqouted)@dbnameas a parameter that may have been quoted, hence the attempt to match it with the value from the table with or without quoting. Yes, they should be usingsys.databases.