2

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
5
  • 1
    Aside: Rather than '[' + name + ']' you ought to be using QuoteName to quote an object name. Commented May 2, 2020 at 3:15
  • @HABO, thanks, I will definitely change it to use QuoteName instead. Commented May 2, 2020 at 3:35
  • You don't need to bother with that anyway as the name in dbo.sysdatabases will be stored unquoted. And dbo.sysdatabases is deprecated (replaced by sys.databases where it will also be unqouted) Commented May 2, 2020 at 9:12
  • @MartinSmith - In this case it appears that the OP is using @dbname as 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 using sys.databases. Commented May 2, 2020 at 13:32
  • Ah yes, missed that. DB_ID doesn't care if it is quoted or not anyway Commented May 2, 2020 at 14:12

1 Answer 1

4

Wrap the expression using the potentially non existent database in EXEC so it is only compiled if that branch is taken.

I used some shorter idioms for checking database and column existence. If you stick with your existing one for columns it will need to go inside the string that is EXECed with the quotes doubled up to escape them.

DECLARE @dbname sysname
SET @dbname = N'Courses'

IF DB_ID(@dbname) IS NOT NULL
  BEGIN
    IF COL_LENGTH('Courses.dbo.Course','isAvailableOnline') IS NULL
    BEGIN
       EXEC('ALTER TABLE Courses.dbo.Course ADD isAvailableOnline BIT NULL')
    END
  END
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.