Consider the following script:
DECLARE @path varchar(MAX)
DECLARE @script varchar(MAX)
SET @path = (SELECT physical_name FROM sys.master_files where name = 'master');
SET @path = REPLACE(@path, 'master.mdf', '');
SELECT @path;
SET @script =
'CREATE DATABASE test
ON PRIMARY
(NAME = test_primary,
FILENAME = ''' + @path + 'test_primary.mdf'',
SIZE = 10MB,
FILEGROWTH = 10MB)';
exec(@script);
USE test
When I try to run it all at once I get an error:
Msg 911, Level 16, State 1, Line 31
Database 'test' does not exist. Make sure that the name is entered correctly.
If I first run exec and then separately run USE it all goes fine.
The question is, how can I work-around it, so that it’d be possible to run the whole script at once with no errors?
SQL Server compiles the code for one batch at a time. When your code is compiled the database does not exist.
Add a batch separator before
use test.