DECLARE @i int
DECLARE @j int
DECLARE @ChannelId int
DECLARE @SensorId int
DECLARE @numChannelRows int
DECLARE @numSensorRows int
DECLARE @UserValue1 NVARCHAR(50)
DECLARE @UserValue2 NVARCHAR(50)
DECLARE @UserValue3 NVARCHAR(50)

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 @UserValue1 = (SELECT UserValue1 FROM SensorsAnalog WHERE SensorId = @SensorId)
				INSERT INTO GroupChannelSettings VALUES (@ChannelId, 23, @UserValue1)
				SET @UserValue2 = (SELECT UserValue2 FROM SensorsAnalog WHERE SensorId = @SensorId)
				INSERT INTO GroupChannelSettings VALUES (@ChannelId, 24, @UserValue2)
				SET @UserValue3 = (SELECT UserValue3 FROM SensorsAnalog WHERE SensorId = @SensorId)
				INSERT INTO GroupChannelSettings VALUES (@ChannelId, 25, @UserValue3)

				SET @j = @j + 1
			END

		DROP TABLE #sensoridtable

		SET @i = @i + 1
	END
DROP TABLE #channelidtable