创建视图错误,因为语句必须只是批处理中的一个

时间:2016-06-15 07:58:46

标签: sql sql-server

这是我第一次尝试在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;

2 个答案:

答案 0 :(得分:3)

您无法在函数内创建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;

答案 1 :(得分:0)

MSDN文档明确说明如下:

以下语句不能在存储过程正文的任何​​位置使用

  

创建AGGREGATE
  创建计划
  SET SHOWPLAN_TEXT
  创建默认
  创建或更改触发器   SET SHOWPLAN_XML
  创建或更改功能
  创建或更改视图
  使用database_name
  创建或更改程序
  SET PARSEONLY
  创造规则
  SET SHOWPLAN_ALL