Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am writting a dynamic sql to drop and create view in different database.

So I wrote:

set @CreateViewStatement = 
                USE ['+ @DB +'];
                CREATE VIEW [dbo].[MyTable]

                SELECT ........something
exec (@CreateViewStatement)

It gives me error:

'CREATE VIEW' must be the first statement in a query batch.

If I remove the USE DATABASE statement it works fine, but then the database is not specify anymore....

How can I solve this problem?

share|improve this question
up vote 23 down vote accepted

You can use nested EXEC calls. The database context changed by the USE persists to the child batch.


SET @DB = 'tempdb'

DECLARE @CreateViewStatement NVARCHAR(MAX) 
SET @CreateViewStatement = '
      USE '+ QUOTENAME(@DB) +';
             CREATE VIEW [dbo].[MyTable] AS
             SELECT 1 AS [Foo]

EXEC (@CreateViewStatement)
share|improve this answer
+1 - If you script out views using SMO this is how the framework does it as well - definitions are executed in dynamic SQL to get around the restriction – JNK Feb 2 '12 at 16:44
oooh, it worked! Thanks! – King Chan Feb 2 '12 at 16:48
@KingChan - you can both upvote and accept, FYI ;) – JNK Feb 2 '12 at 16:54
@JNK +1 of course~ :) – King Chan Feb 2 '12 at 17:42
definitely worked!! although i used it, wih many variables inside the nested query so i was a headache becuz of the quote handling! great solution though ! – user20268 Feb 18 '13 at 1:49

One way I have handled when run into this case is placing GO after use statement.

set @CreateViewStatement = 
  USE ['+ @DB +']; GO
  CREATE VIEW [dbo].[MyTable]

  SELECT ........something'
exec (@CreateViewStatement)
share|improve this answer
Just so you know, GO statment won't runs in exec – King Chan Feb 2 '12 at 17:44
This won't work in the context of dynamic SQL. GO is a batch delimiter in the client tools not a TSQL keyword. – Martin Smith Feb 2 '12 at 17:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.