SQL Server stored procedure: UPDATE with lowest value, else INSERT if there's already a value -
migrating 20k rows or @ once, hopefully. been away sql on 10 years , struggling. i may going entirely wrong. need update table1.value2 lowest value table2.value1 , unless there's value2 . if latter, need insert row value table1.value1 . table1.value1 lowest value of each id row. value2 needs next lowest. current table1: id1, 123, [empty] id4, 111, [empty] current table2: id1, 224 id1, 331 id4, 210 id4, 551 table1 - desired state: id1, 123, 224 id1, 331, [empty] id4, 111, 210 id4, 551, [empty] table2 - desired state: [empty] here's tried , update section works correctly. insert never works. think coded myself corner. create procedure dbo.broken --declare variables declare @id int, @value1 int, @value2 int, @tmpvalue int --declare counter declare @counter int set @counter = 1 --declare cursor query declare ctable1 cursor read_only select id,value1, value2 table1 ...