CREATE VIEW must be the only statement in the batch
Just as the error says, the CREATE VIEW
statement needs to be the only statement in the query batch.
You have two option in this scenario, depending on the functionality you want to achieve:
Place the
CREATE VIEW
query at the beginningCREATE VIEW showingasselect tradename, unitprice, GenericFlagfrom Medicine;with ExpAndCheapMedicine(MostMoney, MinMoney) as( select max(unitprice), min(unitprice) from Medicine),findmostexpensive(nameOfExpensive) as( select tradename from Medicine, ExpAndCheapMedicine where UnitPrice = MostMoney),findCheapest(nameOfCheapest) as( select tradename from Medicine, ExpAndCheapMedicine where UnitPrice = MinMoney )
Use
GO
after the CTE and before theCREATE VIEW
query-- Option #2
with ExpAndCheapMedicine(MostMoney, MinMoney) as( select max(unitprice), min(unitprice) from Medicine),findmostexpensive(nameOfExpensive) as( select tradename from Medicine, ExpAndCheapMedicine where UnitPrice = MostMoney),findCheapest(nameOfCheapest) as( select tradename from Medicine, ExpAndCheapMedicine where UnitPrice = MinMoney)GO CREATE VIEW showingasselect tradename, unitprice, GenericFlagfrom Medicine;
I came across this question when I was trying to create a couple of views within the same statement, what worked well for me is using dynamic SQL.
EXEC('CREATE VIEW V1 as SELECT * FROM [T1];'); EXEC('CREATE VIEW V2 as SELECT * FROM [T2];');
You can also use :
CREATE VIEW vw_test1 AS SELECT [Name] FROM dbo.test1;GOCREATE VIEW vw_test2 AS SELECT [Name] FROM dbo.test2;GO--If you need to grant some rights, just use :GRANT SELECT ON vw_test....
It's easy to understand and avoid dynamic SQL (even if dynamic SQL also works )