﻿CREATE PROCEDURE [dbo].[sp_AnalogDiagnosticsUpdateInsert]
	@Id                 BIGINT NULL,
	@DiagnosticRunId	BIGINT,
	@Excitation	        Float NULL,
	@ExcitationStatus   SmallInt,
	@Offset				Float NULL,
	@OffsetStatus       SmallInt,
	@ActualRange		Float NULL,
	@ActualRangeStatus  SmallInt,
	@Shunt				Float NULL,
	@ShuntStatus		SmallInt,
	@Noise				Float NULL,
	@NoiseStatus		SmallInt,
	@SensorId			Int NULL,
	@SensorSerialNumber NVARCHAR(255),
	@DasId				Int NULL,
	@DASSerialNumber    NVARCHAR(50),
	@DASChannelIdx		Int,
	@UserCode			NVARCHAR(50),
	@UserChannelName    NVARCHAR(50),
	@IsoCode			NVARCHAR(50),
	@IsoChannelName		NVARCHAR(50),
	@ScaleFactorMV		Float,
	@CalibrationRecordId INT NULL,
	@CalibrationRecord  NVARCHAR(MAX),
	@Timestamp			DateTime,
	@errorNumber		INT OUTPUT,
	@errorMessage		NVARCHAR (255) OUTPUT,
	@new_id				BIGINT OUTPUT
AS
BEGIN

	set @errorNumber = 0; 	set @errorMessage = space(0);
	
	IF NOT EXISTS(SELECT [Id] FROM [dbo].[DiagnosticRuns] WHERE [Id]=@DiagnosticRunId)
	BEGIN
		SET @ErrorNumber = 100;
		SET @ErrorMessage ='Invalid Diagnostic Id';
	END
	ELSE if(exists(select Id from [dbo].[DiagnosticRuns] where Id = @Id))
	begin
		set @new_id = @Id;
		UPDATE [dbo].[AnalogDiagnostics] SET [Shunt]=@Shunt, [ShuntStatus]=@ShuntStatus, [Excitation]=@Excitation, [ExcitationStatus]=@ExcitationStatus, [Offset]=@Offset, [OffsetStatus]=@OffsetStatus, [ActualRange]=@ActualRange, [ActualRangeStatus]=@ActualRangeStatus,[Noise]=@Noise,[NoiseStatus]=@NoiseStatus,[SensorId]=@SensorId,[SensorSerialNumber]=@SensorSerialNumber, [DASId]=@DasId,[DASSerialNumber]=@DASSerialNumber, [DASChannelIdx]=@DASChannelIdx, [UserCode]=@UserCode, [UserChannelName]= @UserChannelName, [IsoCode]=@IsoCode, [IsoChannelName]=@IsoChannelName, [ScaleFactor]=@ScaleFactorMV, [CalibrationRecordId]=@CalibrationRecordId, [CalibrationRecordXML]=@CalibrationRecord, [Timestamp]=@Timestamp;
	end
	else
	begin
		INSERT INTO [dbo].[AnalogDiagnostics]  ([Shunt], [ShuntStatus], [DiagnosticRunId], [Excitation], [ExcitationStatus], [Offset], [OffsetStatus], [ActualRange], [ActualRangeStatus], [Noise], [NoiseStatus], [SensorId], [SensorSerialNumber], [DASId], [DASSerialNumber], [DASChannelIdx], [UserCode], [UserChannelName], [IsoCode], [IsoChannelName], [ScaleFactor], [CalibrationRecordId], [CalibrationRecordXML], [Timestamp]) VALUES (@Shunt, @ShuntStatus, @DiagnosticRunId, @Excitation, @ExcitationStatus,@Offset,@OffsetStatus,@ActualRange,@ActualRangeStatus,@Noise,@NoiseStatus,@SensorId,@SensorSerialNumber,@DasId,@DASSerialNumber,@DASChannelIdx,@UserCode,@UserChannelName,@IsoCode,@IsoChannelName,@ScaleFactorMV,@CalibrationRecordId,@CalibrationRecord,@Timestamp);
		SET @new_id = SCOPE_IDENTITY();
	end
	IF(@@error != 0)
		BEGIN
			SET @errorNumber = error_number()
			SET @errorMessage = error_message()
		END
END