SQL Server Error 111: “…must be the first statement in a query batch”

In SQL Server, a batch is a group of one or more T-SQL statements sent at the same time from an application to SQL Server for execution.

If you encounter an error like this:

Msg 111, Level 15, State 1, Line 2
'CREATE VIEW' must be the first statement in a query batch.

It’s probably because you’re combining the statement with other statements in the same batch, which is not allowed in batches.

The first part of the error message will depend on the actual statement that you’re using in your batch. In my case it’s CREATE VIEW, but it could just as easily be CREATE PROCEDURE, CREATE FUNCTION, etc if those are the statements you’re using.

Example

Here’s an example of some code that would cause this error:

DROP VIEW IF EXISTS vAllCustomers;

CREATE VIEW vAllCustomers AS
SELECT * FROM Customers;

Result:

Msg 111, Level 15, State 1, Line 3
'CREATE VIEW' must be the first statement in a query batch.

In my case, I’m trying to run two statements; a DROP VIEW statement and a CREATE VIEW statement.

The rules of a T-SQL batch state that the CREATE VIEW statement cannot be combined with other statements in the same batch.

In other words, CREATE VIEW can be the only statement in its batch.

How to Fix the Error

We can fix the above error by simply adding a batch separator after the first statement.

In SQL Server, the GO keyword signals the end of a batch. More specifically, SQL Server utilities interpret GO as a signal that they should send the current batch of T-SQL statements to an instance of SQL Server.

So we could change the previous statement to this:

DROP VIEW IF EXISTS vAllCustomers;
GO
CREATE VIEW vAllCustomers AS
SELECT * FROM Customers;
GO

Adding GO fixes the issue by separating the statements into two separate batches.

Note that GO is not actually part of T-SQL. It’s a command that is recognised by SQL Server utilities for the purpose of separating statements into batches.

You may be able to change the batch separator, depending on the tool you use to connect to SQL Server. For example, in SSMS, you can find this option by going to: Tools > Options > Query Execution > SQL Server and look for an option that says something like “Specify a word or character that can be used to separate batches”.