I have the following code at the start of a T-SQL script to declare some variables then check if a database exists and to create it if not, followed by a USE statement for the database. The database is not being created so the USE fails. What is the reason this does not work?
DECLARE @new_doctypes varchar(40) = 'my_new_doctypes';
DECLARE @new_phrases varchar(40) = 'my_new_phrases';
DECLARE @new_map varchar(40) = 'my_new_typephrase_map';
DECLARE @error bit = 0;
IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'AV_Maint_New')
BEGIN
PRINT 'Error: Database AV_Maint_New already exists.';
SET @error = 1;
END
ELSE
BEGIN
CREATE DATABASE AV_Maint_New;
END
USE AV_Maint_New;
CodePudding user response:
SSMS is parsing that the database doesn't exist, before you execute it, and it doesn't understand how to follow if paths.
You need a GO between the IF structure and the USE command:
...
ELSE
BEGIN
CREATE DATABASE AV_Maint_New;
END
GO
USE AV_Maint_New;
