16

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]
 AS
 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?

asked Feb 2, 2012 at 16:30

2 Answers 2

25

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

DECLARE @DB SYSNAME
SET @DB = 'tempdb'
DECLARE @CreateViewStatement NVARCHAR(MAX) 
SET @CreateViewStatement = '
 USE '+ QUOTENAME(@DB) +';
 EXEC(''
 CREATE VIEW [dbo].[MyTable] AS
 SELECT 1 AS [Foo]
 '')
 '
EXEC (@CreateViewStatement)
answered Feb 2, 2012 at 16:37
5
  • 1
    +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 Commented Feb 2, 2012 at 16:44
  • 1
    @KingChan - you can both upvote and accept, FYI ;) Commented Feb 2, 2012 at 16:54
  • @JNK +1 of course~ :) Commented Feb 2, 2012 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 ! Commented Feb 18, 2013 at 1:49
  • You are a hero. Will name my firstborn child after you. Commented May 3, 2017 at 12:16
-1

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]
 AS
 SELECT ........something'
exec (@CreateViewStatement)
answered Feb 2, 2012 at 17:41
2
  • Just so you know, GO statment won't runs in exec Commented Feb 2, 2012 at 17:44
  • 2
    This won't work in the context of dynamic SQL. GO is a batch delimiter in the client tools not a TSQL keyword. Commented Feb 2, 2012 at 17:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.