I’m trying to make a view. So far, I have written this:
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
)
CREATE VIEW showing
as
select tradename, unitprice, GenericFlag
from Medicine;
Unfortunately, I get an error on the line containing CREATE VIEW showing
«CREATE VIEW must be the only statement in the batch»
How can I fix this?!
Mozart
2,1672 gold badges22 silver badges38 bronze badges
asked Dec 3, 2014 at 12:50
1
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 VIEWquery at the beginningCREATE VIEW showing as select tradename, unitprice, GenericFlag from 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
GOafter the CTE and before theCREATE VIEWquery— 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 showing as select tradename, unitprice, GenericFlag from Medicine;
answered Dec 3, 2014 at 12:52
Radu GheorghiuRadu Gheorghiu
20.2k16 gold badges72 silver badges107 bronze badges
9
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];');
answered Jan 8, 2019 at 9:36
MozartMozart
2,1672 gold badges22 silver badges38 bronze badges
1
You can also use :
CREATE VIEW vw_test1 AS SELECT [Name] FROM dbo.test1;
GO
CREATE 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 )
answered Jan 25, 2021 at 11:02
AlexBAlexB
7,33212 gold badges56 silver badges75 bronze badges
Simply use GO before and after creating view it will solve your problem
GO
Create view Vaccinated as
select
location,
population,
vaccination
from Covid
GO
answered Dec 14, 2022 at 6:13
1
use statement terminator ; or use GO after cte statement
answered Feb 4 at 12:36
0
Funny, my issue, creating this error was a missing comma in the select fields )))
Like this:
CREATE VIEW [dbo].[ITEM_VIEW]
AS
SELECT dbo.ORDR.one, CAST(dbo.ORDR.two as varchar) AS order_number
dbo.RDR1.three AS line_number
FROM dbo.RDR1 INNER JOIN
dbo.ORDR ON dbo.RDR1.DocEntry = dbo.ORDR.DocEntry
should be
CREATE VIEW [dbo].[ITEM_VIEW]
AS
SELECT dbo.ORDR.one, CAST(dbo.ORDR.two as varchar) AS order_number,
dbo.RDR1.three AS line_number
FROM dbo.RDR1 INNER JOIN
dbo.ORDR ON dbo.RDR1.DocEntry = dbo.ORDR.DocEntry
answered Jan 27 at 11:16
tomtom
2,2101 gold badge24 silver badges27 bronze badges
Basically its what the title says. This is my code.
USE Assignment2;
GO
/* Player View (2 marks)
Create a view which shows the following details of all players:
• The ID number of the player
• The first name and surname of the player concatenated and given an alias of “full_name”
• The team ID number of the player (if applicable)
• The team name of the player (if applicable)
• The coach ID number of the player (if applicable)
• The name of the player’s coach (if applicable)
Creating this view requires a select statement using multiple joins and concatenation of names.
Make sure that you use the appropriate type of join to ensure that players without teams or coaches are still included in the results.
*/
-- Write your Player View here
PRINT 'Creating Player View'
CREATE VIEW playerView AS
SELECT player.id, player.firstName + ' ' + player.surname AS 'Full name', player.team, team.name, player.coach, coach.firstName, coach.surname
FROM player
LEFT OUTER JOIN team
ON player.team = team.id
LEFT OUTER JOIN player as coach
ON player.coach = coach.id;
GO
/* Race View (3 marks)
Create a view which shows the following details of all races:
• All of the columns in the race table
• The name of the race type, course and team involved in the race
• The full name of the player observing the race and the full name of the MVP (if applicable)
• A calculated column with an alias of “unpenalised_score”, which adds the points penalised to the final score
Creating this view requires a select statement using multiple joins and concatenation of names.
Make sure that you use the appropriate type of join to ensure that races without MVPs are still included in the results.
*/
-- Write your Race View here
PRINT 'Creating Race View'
CREATE VIEW raceView AS
SELECT race.id, race.dateOfRace, race.raceType, raceType.name AS raceTypeName, race.course, course.name AS courseName, race.team, team.name AS teamName, race.observer, obs.firstName + ' ' + obs.surname AS observer_name, race.mvp, mvp.firstName + ' ' + mvp.surname AS mvp_name, race.pointsPenalised, race.finalScore + race.pointsPenalised AS unpenalised_score, race.finalScore
FROM race
INNER JOIN raceType
ON race.raceType = raceType.id
INNER JOIN course
ON race.course = course.id
INNER JOIN team
ON race.team = team.id
LEFT OUTER JOIN player AS mvp
ON race.mvp = mvp.id
LEFT OUTER JOIN player AS obs
ON race.observer = obs.id;
GO
SELECT *
FROM playerView
SELECT *
FROM raceView
/* Additional Information:
The views are very convenient replacements for the tables they represent, as they include the names and calculated values that you will often need in queries.
You are very much encouraged to use the views to simplify the queries that follow. You can use a view in a SELECT statement in exactly the same way as you can use a table.
If you wish to create additional views to simplify the queries which follow, include them in this file.
*/
When I run each CREATE VIEW separately, it seems to run it correctly with no errors. But when I try to run the entire script, it gives me this error.
Msg 111, Level 15, State 1, Line 20
‘CREATE VIEW’ must be the first statement in a query batch.
Msg 111, Level 15, State 1, Line 15
‘CREATE VIEW’ must be the first statement in a query batch.
Msg 208, Level 16, State 1, Line 2
Invalid object name ‘playerView’.
Before attempting to run this script, I first delete database, recreate the tables, populate them and then run this script.
Any ideas where I’m going wrong?
|
MIX_Gamer 0 / 0 / 0 Регистрация: 03.12.2020 Сообщений: 6 |
||||
|
1 |
||||
|
03.12.2020, 20:48. Показов 6922. Ответов 6 Метки microsoft sql server studio, sql, test (Все метки)
Microsoft SQL Server Management Studio 18 показывает ошибку: «CREATE VIEW должен быть единственным оператором в пакете».
Пожалуйста, помогите кто разбирается! Буду очень благодарен!
0 |
|
5319 / 4254 / 1051 Регистрация: 29.08.2013 Сообщений: 26,797 Записей в блоге: 3 |
|
|
03.12.2020, 22:10 |
2 |
|
а почему у вас 2 запроса в вьюхе?
0 |
|
1925 / 1370 / 275 Регистрация: 14.08.2018 Сообщений: 4,506 Записей в блоге: 4 |
|
|
04.12.2020, 08:34 |
3 |
|
Для разделения пакетов в SSMS можно использовать оператор
0 |
|
0 / 0 / 0 Регистрация: 03.12.2020 Сообщений: 6 |
|
|
04.12.2020, 09:25 [ТС] |
4 |
|
Я выполняю тестирование TPC-H на MS SQL Server. Приложил проект с GitHub. У меня не выполняется именно 15 запрос. Как бы я не старался его выполнить. Может подскажите готовый код, который будет работать на Microsoft SQL Server Management Studio 18.
0 |
|
2 / 1 / 1 Регистрация: 03.12.2020 Сообщений: 14 |
|
|
04.12.2020, 20:49 |
5 |
|
0 |
|
invm 3365 / 2061 / 736 Регистрация: 02.06.2013 Сообщений: 5,045 |
||||
|
04.12.2020, 21:42 |
6 |
|||
|
РешениеMIX_Gamer,
1 |
|
0 / 0 / 0 Регистрация: 03.12.2020 Сообщений: 6 |
|
|
04.12.2020, 22:14 [ТС] |
7 |
|
Всем спасибо за ответ! Со всем разобрался.
0 |
- Remove From My Forums
-
Question
-
I have a problem that I have been unable to solve. I have a stored procedure in a database on server A that needs to create an indexed view in a database on server B. (The environment is SQL Server 2005.) The procedure on server A does
the following: (The EXEC statement inside the quotes is really a variable in my procedure, I’ve just substituted the value to make the example understandable.)EXEC sp_executesql ‘EXEC
[ServerB].[Database].dbo.sp_executesql @sqlStatement;’The «outer» sp_executesql causes the «inner» sp_executesql to be execute within the database on server B. (@sqlStatement contains the CREATE VIEW syntax.) I am able to create the view that I want to index with no problem. However, when
I attempt to create an index on the view in a subsequent step, it fails with the message «Cannot create index. Object ‘_dta_mv_51’ was created with the following SET options off: ‘QUOTED_IDENTIFIER’«. Fair enough,
but if I attempt to precede my CREATE VIEW statement with the required QUOTED_IDENTIFIER, I receive an error to the effect that «‘CREATE VIEW’ must be the first statement in a query batch«.I’m not sure how to get around this problem. Does anyone have the answer? SQL Server 2008 doesn’t object to indexing a view that was created with QUOTED_IDENTIFIER off, but that’s not doing me any good.
Thanks.
Answers
-
> Here is what my testing has shown. First, an indexed view consists of two things, the view and the index on the view. To create the indexed view, you would issue a CREATE VIEW followed by a CREATE INDEX. In SS 2005, you must
precede the CREATE VIEW with a SET QUOTED_IDENTIFIER ON statement. However, in SS 2008, this is not required.Again, this has nothing to do with the version of SQL Server. Both SQL 2005 and SQL 2008 save the setting of QI with the view definition, and both require QI to be ON for an indexed view.
This script fails on both SQL 2005 and SQL 2008:
USE tempdb go CREATE TABLE mybasetable (a int NOT NULL PRIMARY KEY) go SET QUOTED_IDENTIFIER OFF go CREATE VIEW myview WITH SCHEMABINDING AS SELECT a FROM dbo.mybasetable WHERE a > 0 go CREATE UNIQUE CLUSTERED INDEX vix ON myview(a) go DROP VIEW myview DROP TABLE mybasetable go SET QUOTED_IDENTIFIER ON
You can do the nested EXEC kludge, but the real problem is why QUOTED_IDENTIFIER is OFF on your SQL Server 2005 machine. It shouldn’t be.
You said that you createing this from a stored procedure (which I think is a dubious practice), but that is another story. Could you disclose the full code? I got the impression that were linked servers involved, could you confirm this? If that is the case,
I would think there is something bad with the definition of the linked server.
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx-
Marked as answer by
Wednesday, September 22, 2010 7:24 AM
-
Marked as answer by
Как показано на рисунке выше, SQL Server выдает сообщение об ошибке.
Из онлайновой информации видно, что оператор CREATE VIEW имеет условие, что оператор должен быть выполнен первым, и на рисунке есть использование xsgl, поэтому система выдает ошибку.Решение таково: добавьте инструкцию GO для брата выше и ниже инструкции CREATE VIEW.
Интеллектуальная рекомендация
У вас есть ошибка в синтаксисе SQL (ошибка)
Эта ошибка возникает, поэтому я использую ключевое слово «Заказ» базы данных в качестве имени моей таблицы данных, вызывая мою «выберите * от заказа», чтобы найти ошибку!…
Ошибка: у вас есть ошибка в синтаксисе SQL
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘? and password=?’ at line 1 Первые два дня провели ди…
При записи pl / sql выдается ошибка
При записи pl / sql выдается ошибка View Code Обратите внимание: в строке используются одинарные кавычки, а не двойные. posted @ 2017-06-14 16:25 Йогурт с зеленым чаем читать(…) Комментарии (…) ре…
Вам также может понравиться
Ошибка Centos7yum synaxError: неверный синтаксис
После установки Python3 для изменения установки проверки мягкой ссылки вы обнаружите, что YUM не может быть использован, и возникнут следующие ошибки: Это связано с тем, что yum Centos по умолчанию за…
Ошибка ipython: синтаксисратор: неверный синтаксис
Когда диск C слишком мал, при установке Pycharm и Anaconda не существует пути установки по умолчанию, который вызывает многие проблемы в будущем. Это один из них: Конфигурация окружающей среды: Операц…
Оператор создания SQL Server
Выполнить операторы SQL в программном обеспечении SQL Server Management Studio: Правая сторона принадлежит оператору SQL, а затем нажмите…
Ошибка синтаксиса Mapper -SQL
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘formmybatis.user where name = ‘dayang’’ a…
Это первый раз, когда я пытаюсь создать представление в t-sql, но получаю сообщение об ошибке: CREATE VIEW должен быть единственным оператором в пакете.
Почему он выдает мне эту ошибку и как ее можно исправить?
Я посмотрел на несколько примеров, но все еще не уверен, что мне нужно делать.
CREATE PROCEDURE [dbo].[League_Table_Insert]
@LeagueName VARCHAR(30)
AS
SET NOCOUNT ON
BEGIN
CREATE VIEW League_Table AS
SELECT
TeamName AS Team,
COUNT(*) Played,
COUNT(CASE WHEN HomeScore > AwayScore THEN 1 END) Wins,
COUNT(CASE WHEN AwayScore > HomeScore THEN 1 END) Losses,
COUNT(CASE WHEN HomeScore = AwayScore THEN 1 END) Draws,
SUM(HomeScore) Goals_Scored,
SUM(AwayScore) Goals_Against,
SUM(HomeScore) - SUM(AwayScore) Goal_Difference,
SUM(
CASE WHEN HomeScore > AwayScore THEN 3 ELSE 0 END
+ CASE WHEN HomeScore = AwayScore THEN 1 ELSE 0 END
) Points
FROM
(
SELECT TeamName, HomeScore, AwayScore FROM dbo.Team t INNER JOIN dbo.Fixture f ON t.TeamID = f.HomeTeamID INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID WHERE LeagueName = @LeagueName
UNION ALL
SELECT TeamName, HomeScore, AwayScore FROM dbo.Team t INNER JOIN dbo.Fixture f ON t.TeamID = f.HomeTeamID INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID WHERE LeagueName = @LeagueName
) matches
GROUP BY TeamName
ORDER BY Points DESC, Goal_Difference DESC;
Вы не можете создать VIEW внутри функции. Кроме того, вы не можете использовать переменную внутри VIEW. Вам нужна функция с табличным значением. Вот сценарий создания встроенной функции с табличным значением (iTVF):
CREATE FUNCTION dbo.League_Table (
@LeagueName VARCHAR(MAX)
)
RETURNS TABLE
AS
RETURN
SELECT
TeamName AS Team,
COUNT(*) Played,
COUNT(CASE WHEN HomeScore > AwayScore THEN 1 END) Wins,
COUNT(CASE WHEN AwayScore > HomeScore THEN 1 END) Losses,
COUNT(CASE WHEN HomeScore = AwayScore THEN 1 END) Draws,
SUM(HomeScore) Goals_Scored,
SUM(AwayScore) Goals_Against,
SUM(HomeScore) - SUM(AwayScore) Goal_Difference,
SUM(
CASE WHEN HomeScore > AwayScore THEN 3 ELSE 0 END
+ CASE WHEN HomeScore = AwayScore THEN 1 ELSE 0 END
) Points
FROM
(
SELECT TeamName, HomeScore, AwayScore FROM dbo.Team t INNER JOIN dbo.Fixture f ON t.TeamID = f.HomeTeamID INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID WHERE LeagueName = @LeagueName
UNION ALL
SELECT TeamName, HomeScore, AwayScore FROM dbo.Team t INNER JOIN dbo.Fixture f ON t.TeamID = f.HomeTeamID INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID WHERE LeagueName = @LeagueName
) matches
GROUP BY TeamName;
Обратите внимание, что я удалил предложение ORDER BY, потому что оно не разрешено во встроенных функциях. В противном случае вы получите сообщение об ошибке:
Предложение ORDER BY недопустимо в представлениях, встроенных функциях, производных таблицах, подзапросах и общих табличных выражениях, если также не указано TOP, OFFSET или FOR XML.
Затем, чтобы использовать его:
SELECT *
FROM dbo.League_Table('Sample League Name') s
ORDER BY Points DESC, Goal_Difference DESC;
person
Felix Pamittan
schedule
15.06.2016

Сообщение было отмечено MIX_Gamer как решение