Mi declaración de actualización se está procesando antes de un INSERT INTO previamente indicado

I'm trying to update 37k records with a new value, but prior to that I'm trying to enter an Audit trail record to record the previous value. What I'm running into is that the Update command, even though comes after the INSERT INTO command, the INSERT INTO command's "Previous Value" is showing the new value. It appears that the Update command is being processed first.

WHILE @iLP <=@cntDeal_SD
BEGIN
-- History Change
SET @PrevSettleDate=(SELECT SettleDate FROM Deal WHERE DealID=@Deal_ID)

INSERT INTO History
    (ItemKey,LoginID,TimeStamp,HowChanged,FieldChanged,PreviousValue,NewValue,Comment,Created)
    VALUES ('CDeal' + CAST(@Deal_ID AS varchar(10)),1,GETDATE(), 'M','SettleDate', ISNULL(@PrevSettleDate,'NULL'), '3/02/2012', 'TSR5691', 0)


-- Record Change 
SET @Deal_ID = (SELECT DealID FROM @tblDeal_SD WHERE Row = @iLP)
UPDATE Deal SET SettleDate = '3/02/2012' WHERE DealID=@Deal_ID


SET @iLP=@iLP + 1
END

[Editar] Just realized that my SET @Deal_ID statement falls after my INSERT INTO.

While I had realized earlier that I need my INSERT INTO to be posted before my UPDATE, I failed to move the SET statement that everything was based off of.

Mi error.

preguntado el 09 de marzo de 12 a las 16:03

2 Respuestas

No, the problem is that you're;

  • Reading @PrevSettleDate from Deal @Deal_ID.
  • Writing @PrevSettleDate to History for Deal @Deal_ID - so far so good.
  • Updating @Deal_ID to point to the siguiente Deal - this is where you go wrong.
  • Actualizando el siguiente deal's date.
  • Going back to the beginning, reading PrevSettleDate from the deal you just updated.
    ...

If you move the updating of @Deal_ID to the start of the loop, things should just work.

respondido 09 mar '12, 17:03

I'd use the OUTPUT clause of the update statement. This will let you save old values into a table variable, or even directly into the history table. You can do all of the updates at once this way.

http://msdn.microsoft.com/en-us/library/ms177564.aspx

respondido 09 mar '12, 23:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.