I need to compare 2 consecutive rows in the same table. If the data is missing in the second row, I should update it with the first row’s data.
For Eg:
Row EmpID DATE PosID EmpStatus EmpDept EmpVP
----------------------------------------------------------------------
1 21 2010-12-31 NULL TC NULL 40
2 21 2010-01-25 90156840101 NULL 407 NULL
3 21 2003-11-25 NULL AC NULL NULL
First Iteration: Since Row1 EmpStatus = TC, I want to Update the EmpStatus on Row2 to TC (Since its NULL) and EmpVP to 40 on Row2, as shown below:
Row EmpID DATE PosID EmpStatus EmpDept EmpVP
----------------------------------------------------------------------
1 21 2010-12-31 NULL TC NULL 40
2 21 2010-01-25 90156840101 TC 407 40
3 21 2003-11-25 NULL AC NULL NULL
Second Iteration: Since PositionID is NULL on Row3, I want to update Row3 with the PositionID of Row2. Since Row2 now has EmpStatus = TC, I want to compare the row2 and row3 data. Since Row3 has a new value, I want to retain the new value “AC”. But at the same time I want to update the value of EmpDept of Row3 = 40 since it’s NULL. The desired results are shown below:
Row EmpID DATE PosID EmpStatus EmpDept EmpVP
----------------------------------------------------------------------
1 21 2010-12-31 NULL TC NULL 40
2 21 2010-01-25 90156840101 TC 407 40
3 21 2003-11-25 90156840101 AC 407 40
I am working on historical data load and I have to build records going backwards in terms of Dates.
Can anyone please tell me how to code this?
I want to know if we can do these updates, preferably without using cursors, as I have a lot of employees in this table.
Thanks a lot!
This is an iterative process which depends not only on each row visited, but also on data changes made during the processing. I can’t even begin to imagine how you’d do it without cursors.
I think once you resolve yourself to using cursors, then it’s just a matter of determining the rules (in a more general fashion than you’ve presented them) and then implementing those rules using cursors.
This appears to be a one-time process, so I’m not sure I understand why you’d be concerned about writing a routine that uses cursors to process the data, and running it during a maintenance period or just during a slow-usage period.
Here’s some pseudocode for how you might approach this problem (you’ll need to get the actual syntax details from a manual and you’ll need to make sure your business rules are being applied in the right order and the right manner):
BEGIN
END