I am trying to create a dynamic database creation script.
There are many steps, and we often create this database to make the script look something like this.
DECLARE @databaseName nvarchar(100) = 'DatabaseName'
EXEC('/*A lot of database creation code built off of @databaseName*/')
This is all good, with the exception of one view that we would like to create in @databaseName.
I tried four different ways to create this view without success:
My first thought was to simply set up the database context and then create the view in one scenario. Unfortunately, this did not work, because it CREATE VIEWshould be the first statement in its query block ( more ).
EXEC
('
USE [' + @databaseName + ']
CREATE VIEW
')
(1), , CREATE VIEW EXEC. , , @databaseName. , USE EXEC EXEC ().
EXEC ('USE [' + @databaseName + ']')
EXEC ('CREATE VIEW')
, GO, CREATE VIEW . , GO EXEC ().
EXEC
('
USE [' + @databaseName + ']
GO
CREATE VIEW
')
, CREATE VIEW. , CREATE VIEW ().
EXEC ('CREATE VIEW [' + @databaseName + '].[dbo].[ViewName]')
- ? , , Google .