USE statement before CREATE VIEW

sql, sql-server-2008

Solution

You need to make sure that the `CREATE VIEW` is the first statement in a SQL batch - as the error clearly explains. So use this:

USE [jm0235242]
GO      --  put that "GO" separator here! 

CREATE VIEW InvoiceBasic 
AS
SELECT VendorName, InvoiceNumber, InvoiceTotal
FROM Vendors JOIN Invoices ON Vendors.VendorID = Invoices.VendorID

When you run this in SQL Server Management Studio, the `GO` keyword ends a batch and executes it - and the `CREATE VIEW` is now the first statement in the second batch, and it's happy and works, too

Update: the question why exactly the `CREATE VIEW` (and also `ALTER VIEW`, for that matter) must be the first statement of a batch eludes me - I've never heard any compelling explanation for this. Maybe a Microsoftie or someone close to the team knows this and can explain for us all? :-)

Problem

The truth: I am not good at SQL, and after some research I am unable to figure this out. I am reading a chapter on utilizing views and am unable to get this query to work : ``` USE [jm0235242] CREATE VIEW InvoiceBasic AS SELECT VendorName, InvoiceNumber, InvoiceTotal FROM Vendors JOIN Invoices ON Vendors.VendorID = Invoices.VendorID ``` It has issues with my USE statement: 'CREATE VIEW' must be the first statement in a query batch". My question is, how am I supposed to specify which database it is supposed to look at if I cannot use my USE statement. Thanks for any help, and happy thanksgiving!

Original source