--===== Updates the values that already exists and has different antena. -- Updates the value of previous antena with current antena UPDATE Dest SET ubiIdChip = temp.ubiIdChip, ubiIdAntenaAnt = dest.ubiIdAntena, ubiIdAntena = temp.ubiIdAntena, ubiFecha = temp.ubiFecha, ubiBateria = temp.ubiBateria FROM Ubicacion Dest INNER JOIN @Ubicacion temp ON Dest.ubiIDChip = temp.ubiIdChip WHERE dest.ubiIdAntena <> temp.ubiIdAntena --===== Updates the values that already exists and has the same antena. -- Current and Previous antena remains the same. UPDATE Dest SET ubiIdChip = temp.ubiIdChip,-- ubiIdAntenaAnt = ubiIdAntena,-- ubiIdAntena = temp.ubiIdAntena, ubiFecha = temp.ubiFecha, ubiBateria = temp.ubiBateria FROM Ubicacion Dest INNER JOIN @Ubicacion temp ON Dest.ubiIDChip = temp.ubiIdChip AND Dest.ubiIdAntena = temp.UbiIdAntena--===== Insert the values that doesn't exists -- Previous antena set to -1. INSERT INTO Ubicacion SELECT temp.* FROM @Ubicacion temp LEFT JOIN Ubicacion Dest ON Dest.ubiIDChip = temp.ubiIdChip WHERE Dest.ubiIdChip is NULL
--===== Insert the values that doesn't exists -- Previous antena set to -1. INSERT INTO Ubicacion SELECT temp.* FROM @Ubicacion temp LEFT JOIN Ubicacion Dest ON Dest.ubiIDChip = temp.ubiIdChip WHERE Dest.ubiIdChip is NULL
--===== Insert the final result of the split -- as a "table" instead of an "EAV" into @UbicacionINSERT INTO @Ubicacion (ubiIdChip, ubiIdAntena, ubiIdAntenaAnt, ubiFecha, ubiBateria) SELECT MAX(CASE WHEN ColNum = 1 THEN ElementValue END) AS ubiIdChip, MAX(CASE WHEN ColNum = 2 THEN ElementValue END) AS ubiIdAntena, -1, CAST(CAST(MAX(CASE WHEN ColNum = 3 THEN ElementValue END) AS Float) AS DateTime) AS ubiFecha, MAX(CASE WHEN ColNum = 4 THEN ElementValue END) AS ubiBateria FROM @Elements GROUP BY RowNum
--===== Insert the final result of the split -- as a "table" instead of an "EAV" into @Ubicacion INSERT INTO @Ubicacion (ubiIdChip, ubiIdAntena, ubiIdAntenaAnt, ubiFecha, ubiBateria) SELECT MAX(CASE WHEN ColNum = 1 THEN ElementValue END) AS ubiIdChip, MAX(CASE WHEN ColNum = 2 THEN ElementValue END) AS ubiIdAntena, -1 AS ubiIdAntenaAnt, --Previous antena does not exist CAST(CAST(MAX(CASE WHEN ColNum = 3 THEN ElementValue END) AS Float) AS DateTime) AS ubiFecha, MAX(CASE WHEN ColNum = 4 THEN ElementValue END) AS ubiBateria FROM @Elements GROUP BY RowNum
DECLARE @NothingPrevious INT SET @NothingPrevious = -1--===== Insert the final result of the split -- as a "table" instead of an "EAV" into @Ubicacion INSERT INTO @Ubicacion (ubiIdChip, ubiIdAntena, ubiIdAntenaAnt, ubiFecha, ubiBateria) SELECT MAX(CASE WHEN ColNum = 1 THEN ElementValue END) AS ubiIdChip, MAX(CASE WHEN ColNum = 2 THEN ElementValue END) AS ubiIdAntena, @NothingPrevious AS ubiIdAntenaAnt, CAST(CAST(MAX(CASE WHEN ColNum = 3 THEN ElementValue END) AS Float) AS DateTime) AS ubiFecha, MAX(CASE WHEN ColNum = 4 THEN ElementValue END) AS ubiBateria FROM @Elements GROUP BY RowNum