Adam Tolley
Adam Tolley

Reputation: 955

Why can't I create a view inside of a BEGIN ... END block

This code does not work, returning the error:

BEGIN
  CREATE VIEW [dbo].[dummy] AS SELECT 1 AS Dummy
END
GO`

Incorrect syntax near the keyword 'VIEW'.

Why?

Notes:

Upvotes: 19

Views: 17160

Answers (2)

Waleed A.K.
Waleed A.K.

Reputation: 1656

You can use three wayes to create temporary view.

1-AdaTheDev answer.

2-create a temporary table then inserts the value in it e.g create Table #TableName (ID integer). See this Link

3- Using Common Table Expression [With]. See this Link

Upvotes: -2

AdaTheDev
AdaTheDev

Reputation: 147324

It's because CREATE VIEW must be the first statement in a batch as described in this MSDN reference.

Instead, you could do: e.g.

.....
    BEGIN 
        EXECUTE('CREATE VIEW [dbo].[dummy] AS SELECT 1 AS Dummy')
    END

Upvotes: 34

Related Questions