Create view должна быть первой инструкцией в пакетном запросе

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”.

Problem

When you’re executing a CREATE/ALTER statement to create a procedure/view/function/trigger, you get one of the following errors:

‘CREATE/ALTER PROCEDURE’ must be the first statement in a query batch

‘CREATE VIEW’ must be the first statement in a query batch.

‘CREATE FUNCTION’ must be the first statement in a query batch.

‘CREATE TRIGGER’ must be the first statement in a query batch.

You can’t execute these CREATE/ALTER statements with other statements.

Solution

The solution is to execute the CREATE/ALTER statement separately from other statements. How you do that depends on if you’re using SSMS/sqlcmd/osql or executing from C#.

If you’re executing from SSMS (or sqlcmd/osql)

Add the keyword GO right before CREATE statement. This is the default batch separator in SSMS. It splits the query into multiple batches. In other words, it executes the CREATE statement by itself in its own batch, therefore solving the problem of it needing to be the first statement in a batch. Here’s an example:

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'spGetAllPosts') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].spGetAllPosts
GO
CREATE PROCEDURE [dbo].spGetAllPosts
AS
BEGIN
    SELECT * FROM Posts
END
Code language: SQL (Structured Query Language) (sql)

If you’re executing from C#

You can’t use the GO keyword in C#. Instead you have to execute the SQL queries separately. The best way to do that is to execute the first part, then change the CommandText and execute the second part.

using System.Data.SqlClient;

string dropProcQuery = 
	@"IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'spGetAllPosts') AND type in (N'P', N'PC'))
		DROP PROCEDURE[dbo].spGetAllPosts";
		
string createProcQuery = 
	@"CREATE PROCEDURE [dbo].spGetAllPosts
	AS
	BEGIN
		SELECT * FROM Posts
	END";
	
using (var con = new SqlConnection(ConnectionString))
{
	using (var cmd = new SqlCommand(dropProcQuery, con))
	{
	        //Execute the first statement
		con.Open();
		cmd.ExecuteNonQuery();
		
		//Then execute the CREATE statement
		cmd.CommandText = createProcQuery;
		cmd.ExecuteNonQuery();
	}
}

Code language: C# (cs)

Related Articles

This repository was archived by the owner on Sep 30, 2024. It is now read-only.

This repository was archived by the owner on Sep 30, 2024. It is now read-only.

Description

Type

What kind of issue is this?

[x] Bug report.
[ ] Feature request.

Current Behavior

It’s not possible to deploy a view into another database, using ssc push production
Gives this error code:

Error: ‘CREATE VIEW’ must be the first statement in a query batch.

It looks like the current situation doesn’t allow to run two statements in a single batch.

Example view:

if exists (select * from sys.objects where object_id = object_id('[sys].[database_firewall_rules]') and type = 'V')
drop view [sys].[database_firewall_rules]
go

CREATE VIEW sys.database_firewall_rules AS SELECT id, name, start_ip_address, end_ip_address, create_date, modify_date FROM sys.database_firewall_rules_table

Expected behavior

Expected to create the view for me.

Steps to Reproduce

Environment: Azure SQL Database (latest version)
ssc pull development
ssc push production

Other Information

FastAPI и Flask: Отличия, производительность и примеры использования

py-thonny 30.05.2025

Если вы разрабатываете веб-приложения на Python, вы наверняка слышали о Flask и FastAPI. Эти два фреймворка часто становятся предметом жарких дискуссий в сообществе разработчиков. И не без основания. . .

ML.NET и TensorFlow.NET: Умные приложения на C# с машинным обучением

stackOverflow 30.05.2025

Еще совсем недавно, когда речь заходила о машинном обучении, C# разработчики обреченно вздыхали и тянулись к Python. Мир искуственного интеллекта словно был огражден невидимым забором с табличкой. . .

Когда сволочизм стал общественной нормой

kumehtar 30.05.2025

Такой цирк порою видишь, не укладывается в голове.
Там какие-то парни решили прыгать с парашютом. И снимать на камеру. Привязали к себе собаку, и спрыгнули вместе с нею. И подписали «Отважная. . .

Node.js изнутри: Рантайм, архитектура и исходный код

Reangularity 29.05.2025

Node. js представляет собой среду выполнения JavaScript, построенную на движке V8 от Google Chrome. Но называть его просто «средой выполнения» — все равно что назвать швейцарский нож «штукой с. . .

Обработка Big Data на C#

stackOverflow 29.05.2025

C# традиционно оставался в тени Java, Python и Scala, когда речь заходила о работе с большими данными. Многие считали, что . NET недостаточно зрелая для таких задач. Но времена изменились. Язык C#. . .

Как генерируется мир в Minecraft

GameUnited 28.05.2025

Задумывались ли вы когда-нибудь о том, сколько песчинок на нашей планете? По приблизительным подсчетам — более 7 квинтиллионов! Это цыфра с 18 нулями. И все же, это даже не половина количества. . .

Один суперкластер Kubernetes для вообще всего

Mr. Docker 28.05.2025

Ваша компания развивается, количество сервисов множится, команды разработки разрастаются, а DevOps-инженеры начинают напоминать ту самую собаку из мема про «всё нормально, когда ничего не нормально». . . .

CAP-теорема или почему идеальной распределенной системы не существует

ArchitectMsa 28.05.2025

Вы переводите деньги со своего счета на счет друга. Казалось бы, что может быть проще? Вы открываете приложение банка, вводите сумму, жмете кнопку — и деньги мгновенно переходят с одного счета на. . .

Пишем первый чатбот на C# с нейросетью и Microsoft Bot Framework

UnmanagedCoder 28.05.2025

Microsoft Bot Framework представляет собой мощнейший инструментарий для создания разговорных интерфейсов любой сложности. Он предлагает целостную экосистему, которая включает SDK для C#, сервисы. . .

Event-Driven приложения с Apache Kafka и KafkaFlow в .NET

stackOverflow 26.05.2025

Для . NET разработчиков работа с Kafka традиционно сопряжена с определенными трудностями. Официальный клиент Confluent хорош, но часто требует написания большого количества шаблонного кода. Многие. . .

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?

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,1072 gold badges19 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:

  1. Place the CREATE VIEW query at the beginning

    CREATE 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
        )
    
  2. Use GO after the CTE and before the CREATE 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 showing
    as
    select tradename, unitprice, GenericFlag
    from Medicine;
    

answered Dec 3, 2014 at 12:52

Radu GheorghiuRadu Gheorghiu

20k16 gold badges72 silver badges106 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,1072 gold badges19 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,29212 gold badges55 silver badges74 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,1901 gold badge23 silver badges27 bronze badges

Problem

When you’re executing a CREATE/ALTER statement to create a procedure/view/function/trigger, you get one of the following errors:

‘CREATE/ALTER PROCEDURE’ must be the first statement in a query batch

‘CREATE VIEW’ must be the first statement in a query batch.

‘CREATE FUNCTION’ must be the first statement in a query batch.

‘CREATE TRIGGER’ must be the first statement in a query batch.

You can’t execute these CREATE/ALTER statements with other statements.

Solution

The solution is to execute the CREATE/ALTER statement separately from other statements. How you do that depends on if you’re using SSMS/sqlcmd/osql or executing from C#.

If you’re executing from SSMS (or sqlcmd/osql)

Add the keyword GO right before CREATE statement. This is the default batch separator in SSMS. It splits the query into multiple batches. In other words, it executes the CREATE statement by itself in its own batch, therefore solving the problem of it needing to be the first statement in a batch. Here’s an example:

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'spGetAllPosts') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].spGetAllPosts
GO
CREATE PROCEDURE [dbo].spGetAllPosts
AS
BEGIN
    SELECT * FROM Posts
END
Code language: SQL (Structured Query Language) (sql)

If you’re executing from C#

You can’t use the GO keyword in C#. Instead you have to execute the two queries separately. The best way to do that is to execute the first part, then change the CommandText and execute the second part.

using System.Data.SqlClient;

string dropProcQuery = 
	@"IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'spGetAllPosts') AND type in (N'P', N'PC'))
		DROP PROCEDURE[dbo].spGetAllPosts";
		
string createProcQuery = 
	@"CREATE PROCEDURE [dbo].spGetAllPosts
	AS
	BEGIN
		SELECT * FROM Posts
	END";
	
using (var con = new SqlConnection(ConnectionString))
{
	using (var cmd = new SqlCommand(dropProcQuery, con))
	{
	        //Execute the first statement
		con.Open();
		cmd.ExecuteNonQuery();
		
		//Then execute the CREATE statement
		cmd.CommandText = createProcQuery;
		cmd.ExecuteNonQuery();
	}
}

Code language: C# (cs)

#sql #sql-server #view #ssms

#sql #sql-сервер #Вид #ssms

Вопрос:

Microsoft SQL Server Management Studio 18 показывает ошибку:

CREATE VIEW должна быть единственной инструкцией в пакете

После выполнения запроса появляется следующая ошибка:

Неправильный синтаксис вокруг ключевого слова «select»

 create view revenue0 (supplier_no, total_revenue) as
    select
        l_suppkey,
        sum(l_extendedprice * (1 - l_discount))
    from
        lineitem
    where
        l_shipdate >= '1996-05-01'
        and l_shipdate < dateadd(mm,3,cast('1996-05-01' as datetime))
    group by
        l_suppkey;


select
s_suppkey,
s_name,
s_address,
s_phone,
total_revenue
from
supplier,
revenue0
where
    s_suppkey = supplier_no
    and total_revenue = (
        select
            max(total_revenue)
        from
            revenue0
    )
order by
s_suppkey
option (maxdop 2)
drop view revenue0
 

UPD. Я попытался запустить этот метод:

 create view revenue0 (supplier_no, total_revenue) as
    select
        l_suppkey,
        sum(l_extendedprice * (1 - l_discount))
    from
        lineitem
    where
        l_shipdate >= cast('1996-05-01' as datetime)
        and l_shipdate < dateadd(mm, 3, cast('1996-05-01' as datetime))
    group by
        l_suppkey;

go
select
    s_suppkey,
    s_name,
    s_address,
    s_phone,
    total_revenue
from
    supplier,
    revenue0
where
    s_suppkey = supplier_no
    and total_revenue = (
        select
            max(total_revenue)
        from
            revenue0
    )
order by
    s_suppkey;

drop view revenue0;
 

Но в результате выполнения запроса отображается ошибка:
Недопустимое имя объекта «revenue0».
Как только я не изменил свое имя. SQL все равно ругается на это имя.

UPD2. Вопрос был решен самостоятельно. Тема закрыта! Спасибо всем за ваши усилия!

Комментарии:

1. Поместите слово GO после определения представления.

2. Можете ли вы сказать мне, где именно? Я не очень хорошо разбираюсь в SQL. Я буду очень благодарен!

3. group by l_suppkey; GO

4. Неправильный синтаксис вокруг конструкции «go».

5. вы не можете использовать «order by» в представлении, измените свой вид, чтобы не использовать его.

Ответ №1:

Ошибка сообщает, что CREATE VIEW должен быть единственным оператором в пакете. Пакет завершается в SQL Server ключевым словом «GO», как заявил Гордон, поэтому ваш код должен выглядеть следующим образом:

 create view revenue0 (supplier_no, total_revenue) as
    select
        l_suppkey,
        sum(l_extendedprice * (1 - l_discount))
    from
        lineitem
    where
        l_shipdate >= '1996-05-01'
        and l_shipdate < dateadd(mm,3,cast('1996-05-01' as datetime))
    group by
        l_suppkey;

GO -- right here. This ends a batch. Must be on a new line, with no semi-color, or SQL gets pissy. 

select
    s_suppkey,
    s_name,
    s_address,
    s_phone,
    total_revenue
from
    supplier,
    revenue0
where
    s_suppkey = supplier_no
    and total_revenue = (
        select
            max(total_revenue)
        from
            revenue0
    )
order by
    s_suppkey
option (maxdop 2); 

drop view revenue0;
 

Комментарии:

1. Я тестирую «Тесты TPC-H на MS-SQL-Server» этот материал: ссылка . При выполнении этого запроса это должно быть: link .

2. Но у меня, с вашей поправкой, после выполнения SQL-запроса выводится пустая таблица. Время выполнения запроса составляет 0 секунд. Это ненормально.

3. Вы можете помочь переделать этот запрос, чтобы он работал: ссылка .

4. Я уже всю голову сломал с ним. Но этот конкретный запрос не хочет работать. Все остальные работают.

В основном это то, что говорится в названии. Это мой код.

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.
*/

Когда я запускаю каждый CREATE VIEW отдельно, он, кажется, запускает его правильно, без ошибок. Но когда я пытаюсь запустить весь script, он дает мне эту ошибку.

Msg 111, уровень 15, состояние 1, строка 20
«CREATE VIEW» должен быть первым оператором в пакете запросов.
Msg 111, уровень 15, состояние 1, строка 15
«CREATE VIEW» должен быть первым оператором в пакете запросов.
Msg 208, уровень 16, состояние 1, строка 2
Недопустимое имя объекта ‘playerView’.

Прежде чем пытаться запустить этот script, я сначала удаляю базу данных, воссоздаю таблицы, заполняю их, а затем запускаю этот script.

Любые идеи, в которых я ошибаюсь?

Ответ 1

введите GO после PRINT 'Creating Player View' и он должен работать:

PRINT 'Creating Player View'
GO

CREATE VIEW playerView AS

Ответ 2

Пакеты разделяются словом GO — которое является инструкцией для клиентских инструментов, а не SQL Server, в частности, чтобы сообщить этим инструментам, как разделить ваш запрос на партии.

Ошибка говорит вам, что CREATE VIEW должен быть первым оператором в пакете:

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'

GO -->-- New GO here

CREATE VIEW playerView AS 

Итак, я добавил GO до CREATE VIEW

Ответ 3

Поместите код CREATE VIEW внутри EXECUTE

SOME CONDITION..

EXECUTE('CREATE  VIEW vwName...')

Ответ 4

Это обычно происходит, потому что, имея возможность создавать VIEW или любой DBO, вам нужно, чтобы весь script находился внутри транзакции или вам нужно включить
SET QUOTED_IDENTIFIER.

т

USE [yourdatabase]
GO

SET NUMERIC_ROUNDABORT, IMPLICIT_TRANSACTIONS OFF
SET ANSI_PADDING, ANSI_NULLS, QUOTED_IDENTIFIER, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, XACT_ABORT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO

BEGIN TRANSACTION
GO

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

...
...

-- Write your Race View here
PRINT 'Creating Race View'
GO

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 

IF @@ERROR <> 0 BEGIN IF @@TRANCOUNT > 0 ROLLBACK SET NOEXEC ON END
GO

IF @@TRANCOUNT>0 COMMIT TRANSACTION
GO

SET NOEXEC OFF

Новое и полезное:

  • Cream payayor из тайланда инструкция по применению на русском языке
  • Creall crackle инструкция по применению
  • Creality slicer инструкция на русском
  • Creality ender 5 plus инструкция на русском
  • Creality ender 3 инструкция по сборке
  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии
  • Картофелечистка мок 150 инструкция
  • Manduca эрго рюкзак инструкция
  • Slimming tea инструкция по применению
  • Аэртал свечи инструкция по применению
  • Доу респ спиромакс инструкция