I'm trying to automate a sql script to add a column to existing databases on a given system. The script will be run on a system with one database or a different one. The script should not cause error in any of the cases: 1. One of the two databases exists 2. Both databases exist 3. Neither database exists.
I tried this but I keep getting error when the database 'DatabaseName' does not exist. I want the script to be ignored in that case.
IF DB_ID('DatabaseName') IS NOT NULL
BEGIN
PRINT 'DatabaseName Exists'
IF COL_LENGTH('[DatabaseName].[dbo].[Table]', 'NewColumn') IS NULL
BEGIN
ALTER TABLE [DatabaseName].[dbo].[Table]
ADD [NewColumn] bit NOT NULL DEFAULT 0;
PRINT 'Modified DatabaseName.Table'
END
END
ELSE
BEGIN
PRINT 'DatabaseName Does Not Exist'
-- therefore do nothing
END
This gives me the error:
Msg 2702, Level 16, State 2, Line 6
Database 'DatabaseName' does not exist.
I had also tried different variations of Use 'DatabaseName' with the same or similar errors because they are not existent.
To clarify: it is okay if it does not exist. I am just trying to handle the error gracefully so an installation continues