2016-10-10 91 views
1

我定義這個SQL Server的SP,但我收到以下錯誤消息,這是不是很詳細:END關鍵字附近的語法錯誤?

Incorrect syntax near the keyword 'end'. 32 8

我關閉所有BEGINEND,所以我不能讓它發動機爲什麼抱怨。

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有什麼問題?

+1

你有一個開始..年底最低一行沒有任何代碼。 Sql服務器不喜歡,刪除它並且錯誤將會消失 – GuidoG

+1

在@lastReading IS NOT NULL後刪除提及的else部分 –

回答

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

如果聲明ELSE聲明它不能爲空。所以如果你只有BEGINEND它會出錯。

如果您不想使用ELSE,請將其刪除。

1

問題在於其他。您必須在BEGIN和END之間放置代碼。評論做什麼都不是。如果您希望稍後添加其他內容,則可以添加一個SELECT 0,否則應刪除它。

0

BEGIN和END語句需要的代碼

BEGIN 
     -- Do nothing 
     PRINT 1 
    END 
相關問題