I have a script that has a USE DATABASE
statement.
The script runs perfectly fine if the database exists. If it doesn't exist, it fails with the message "the database doesn't exist", which makes perfect sense.
Now, I don't it to fail so I added a check to select if the DB exists on sys.databases (which I will represent here with a IF 1=2
check for the sake of simplicity), so, if the DB exists (1=1), then run the "use" statement.
To my surprise, the script kept failing. So I tried to add a TRY CATCH block. Same result. It seems that the use statement is evaluated prior to anything else, which id quite annoying because now my script may break.
So my question is: how can I have an use
statement on a script to a database that may not exist?
BEGIN TRY
IF (1=1) BEGIN --if DB exists
USE DB_THAT_MAY_NOT_EXIST
END
END TRY
BEGIN CATCH
END CATCH