Please add a GO statement prior to the CREATE VIEW. Please read a detailed explanation of the cause and the solution here.
How to create a view to existing script. CREATE VIEW must be the first statement in a query batch
Hello Community,
I have created a script which creates multiple views based on certain criteria. However, I would like to modify the script such that a new view is created after the scripted has completed with the following code
CREATE VIEW viewplease
AS
SELECT
airport
FROM dbo.account
However, when I add the query to create a view at the end of the script I get back the error:
'CREATE VIEW' must be the first statement in a query batch
Azure SQL Database
SQL Server Other
2 answers
Sort by: Most helpful
-
Alberto Morillo 34,671 Reputation points MVP Volunteer Moderator
2023-02-02T15:22:05.0666667+00:00 -
LiHongMSFT-4306 31,566 Reputation points
2023-02-03T03:27:39.34+00:00 CREATE VIEW must be the first statement in a query batch
Basically, it's not so much that it must be the first statement in the batch, but rather that it must be the only statement in the batch. For the same reason
CREATE PROCEDURE
,CREATE FUNCTION
, etc. all have to be in their own batch ... they need to be compiled independently of other code.One reason is to ensure that anything in the batch created before the object actually exists when it is created, and anything that refers to the object afterward has something to point to. Another is to help prevent want "some other code here" to be included in the definition of the view/stored procedure/function.
In Management Studio, you work around this by placing a
GO
before and after yourCREATE VIEW
code. Note thatGO
is not T-SQL, it is an app-specific batch separator; from other interfaces, you will need to transmit your batches separately in other ways.Again, the answer is in the first sentence: a script to create or alter any module in SQL Server - including views, procedures, functions, and triggers - must be the only statement in the batch.
Refer to Aaron's answer in this thread: Why CREATE VIEW must be first statement in a batch?
Best regards,
Cosmog Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.