END关键字附近的语法错误?

时间:2016-10-10 10:39:34

标签: sql sql-server

我正在定义此SQL Server SP,但是我收到以下错误消息,其中不是很详细:

Incorrect syntax near the keyword 'end'. 32 8

我正在使用BEGIN关闭所有END,因此我无法理解为什么引擎会抱怨。

CREATE PROCEDURE dbo.addReading
    @deviceId int,
    @facilityId int,
    @reading real,
    @insertionTimestamp datetime2,
    @isMeter bit
AS BEGIN
    IF (@isMeter = 1)
        BEGIN
            DECLARE @lastReading real;
            DECLARE @newReading real;

            -- Get last reading
            SELECT @lastReading = lastReading FROM devices
            WHERE facilityId = @facilityId AND id = @deviceId;

            -- Update lastReading with the new one
            UPDATE devices SET lastReading = @reading
            WHERE facilityId = @facilityId AND id = @deviceId;

            IF (@lastReading IS NOT NULL)
                BEGIN
                    SET @newReading = @reading - @lastReading;

                    INSERT INTO readings (deviceId, facilityId, reading, insertionTimestamp)
                    VALUES (@deviceId, @facilityId, @newReading, @insertionTimestamp);
                END
            ELSE
                BEGIN
                    -- Do nothing
                END
        END   -- ---------------------------------- LINE 32 (ERROR HERE!)
    ELSE
        BEGIN
            INSERT INTO readings (deviceId, facilityId, reading, insertionTimestamp)
            VALUES (@deviceId, @facilityId, @reading, @insertionTimestamp);
        END
END

GO

END有什么问题?

4 个答案:

答案 0 :(得分:6)

来自MSDN

BEGIN  
    { sql_statement | statement_block }   
END  

{sql_statement | statement_block}

  

是否定义了任何有效的Transact-SQL语句或语句分组   通过使用语句块。

您需要在BeginEND之间拥有有效的Transact-SQL语句,因此不能拥有此

 ELSE
     BEGIN
     -- Do nothing
     END

如果您的ELSE部分无法执行任何操作,请将其删除

IF (@isMeter = 1)
    BEGIN
        DECLARE @lastReading real;
        DECLARE @newReading real;

        -- Get last reading
        SELECT @lastReading = lastReading FROM devices
        WHERE facilityId = @facilityId AND id = @deviceId;

        -- Update lastReading with the new one
        UPDATE devices SET lastReading = @reading
        WHERE facilityId = @facilityId AND id = @deviceId;

        IF (@lastReading IS NOT NULL)
            BEGIN
                SET @newReading = @reading - @lastReading;

                INSERT INTO readings (deviceId, facilityId, reading, insertionTimestamp)
                VALUES (@deviceId, @facilityId, @newReading, @insertionTimestamp);
            END
    END 

答案 1 :(得分:1)

如果您声明ELSE声明,则该声明无效。因此,如果您只有BEGIN END则会出错。

如果您不想使用ELSE,请将其删除。

答案 2 :(得分:1)

问题在于别的。您必须在BEGIN和END之间放置代码。评论什么也不做。如果你想稍后添加别的东西,你可以添加一个SELECT 0,否则你应该删除它。

答案 3 :(得分:0)

Begin和END语句至少需要一行代码

 BEGIN
      -- Do nothing
        PRINT 1
  END