A.sharif
A.sharif

Reputation: 2017

SQL: Why does "CREATE VIEW" have to be the first statement in a query batch?

In the SQL Server documentation and multiple posts online, it says that

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

There are solutions on how to get around this like this post, which just says to do something like the following:

IF(statement)
BEGIN 
        EXECUTE('CREATE VIEW ...')
END

However it doesn't explain why the actual reason that "CREATE VIEW" has to be the first statement in a query batch. Could someone explain the reason, please? Or know how/where I can find this answer?

Upvotes: 1

Views: 669

Answers (1)

Sean Lange
Sean Lange

Reputation: 33581

About the only valid reason to need this ability is when checking for the existence of an object. This is something that sql server has struggled with because they lack the ability to Create Or Replace like many other databases do. That is how it works in sql server unfortunately.

In SQL Server 2016 they introduced Create Or Alter which deals with this.

As for the reason why this was not introduced earlier this would be a question to ask of the designers of the software which is not really answerable.

Upvotes: 6

Related Questions