DECLARE @i int
DECLARE @j int
DECLARE @ChannelId int
DECLARE @SensorId int
DECLARE @numChannelRows int
DECLARE @numSensorRows int
DECLARE @ZeroMethod NVARCHAR(255)
DECLARE @ZeroMethodType NVARCHAR(255)
DECLARE @ZeroMethodStart NVARCHAR(255)
DECLARE @ZeroMethodEnd NVARCHAR(255)
DECLARE @delimIndex int
DECLARE @startIndex int

DECLARE @channelidtable TABLE (
	idx int Primary Key IDENTITY(1,1)
	, ChannelId int
	)

CREATE TABLE #channelidtable(
	idx int Primary Key IDENTITY(1,1)
	, ChannelId int
	)
	
INSERT #channelidtable
	SELECT DISTINCT ChannelId FROM GroupChannelSettings WHERE ChannelId IN
	  (SELECT Id FROM Channels WHERE SensorId IN
		(SELECT id FROM Sensors WHERE id in 
		  (SELECT SensorId FROM Channels) 
		 AND SensorType = 0))

SET @i = 1
SET @numChannelRows = (SELECT COUNT(*) FROM @channelidtable)
IF @numChannelRows > 0
	WHILE (@i <= (SELECT COUNT(*) FROM @channelidtable))
	BEGIN
		SET @ChannelId = (SELECT ChannelId FROM @channelidtable WHERE idx = @i)

		DECLARE @sensoridtable TABLE (
			sensorIdx int Primary Key IDENTITY(1,1)
			, sensorId int
			)
		CREATE TABLE #sensoridtable(
			sensorIdx int Primary Key IDENTITY(1,1)
			, sensorId int
			)
		INSERT #sensoridtable
			SELECT SensorId FROM Channels WHERE Id = @ChannelId AND SensorId IN
				(SELECT id FROM Sensors WHERE SensorType = 0)

		SET @j = (SELECT MIN(sensorIdx) FROM #sensoridtable)
		SET @numSensorRows = (SELECT COUNT(*) FROM #sensoridtable)
		IF @numSensorRows > 0
			WHILE (@j <= (SELECT COUNT(*) FROM #sensoridtable))
			BEGIN
				SET @SensorId = (SELECT SensorId FROM #sensoridtable WHERE sensorIdx = @j)

				SET @ZeroMethod = (SELECT ZeroMethod FROM SensorCalibrations WHERE 
				                   SensorId = @SensorId AND 
					               ModifyDate = (SELECT MAX (ModifyDate) FROM SensorCalibrations WHERE SensorId = @SensorId))

				SET @startIndex = 0
				SET @delimIndex = CHARINDEX(',', @ZeroMethod, @startIndex)
				SET @ZeroMethodType = SUBSTRING(@ZeroMethod, 0, @delimIndex)
				INSERT INTO GroupChannelSettings VALUES (@ChannelId, 20, @ZeroMethodType)

				IF @ZeroMethodType = 'AverageOverTime'
				BEGIN
					SET @startIndex = @delimIndex + 1
					SET @delimIndex = CHARINDEX(',', @ZeroMethod, @startIndex)
					SET @ZeroMethodStart = SUBSTRING(@ZeroMethod, @startIndex, @delimIndex - @startIndex)
					INSERT INTO GroupChannelSettings VALUES (@ChannelId, 21, @ZeroMethodStart)

					SET @startIndex = @delimIndex + 1
					SET @delimIndex = LEN(@ZeroMethod) + 1
					SET @ZeroMethodEnd = SUBSTRING(@ZeroMethod, @startIndex, @delimIndex - @startIndex)
					INSERT INTO GroupChannelSettings VALUES (@ChannelId, 22, @ZeroMethodEnd)
				END
				ELSE
				BEGIN
					INSERT INTO GroupChannelSettings VALUES (@ChannelId, 21, '-0.05')
					INSERT INTO GroupChannelSettings VALUES (@ChannelId, 22, '-0.02')
				END
				SET @j = @j + 1
			END

		DROP TABLE #sensoridtable

		SET @i = @i + 1
	END

DROP TABLE #channelidtable