I have a script that checks for the existence of the database and if it doesn't exist exits gracefully with some instructions for the user. However when the database doesn't exist, SSMS flags the USE statement as an error and generates its own error without even running my script. So in the following code, the line
SSTDB doesnot exist. Run 1MakeSSTDB.sql first. Exiting script.
never gets executed. If I comment out the USE SSTDB line, then the script works as expected. Any ideas how to get this to work? (Using SqlServer 2014.)
USE master
GO
IF NOT EXISTS (SELECT name
FROM master.dbo.sysdatabases
WHERE ('[' + name + ']' = N'SSTDB' OR name = N'SSTDB'))
BEGIN
Print 'SSTDB doesnot exist. Run 1MakeSSTDB.sql first. Exiting script.'
END
ELSE
BEGIN
Print 'exists'
USE SSTDB
END
Print 'done'
Msg 911, Level 16, State 1, Line 14 Database 'SSTDB' does not exist. Make sure that the name is entered correctly.