I am defining this SQL Server SP, but I am getting the following error message, which is not very detailed:
Incorrect syntax near the keyword 'end'. 32 8
I am closing all BEGIN with an END, therefore I can't get it why is the engine complaining.
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
What is wrong with the END?