If I understand well, you want to exclude the last change done by user 'ADMINEBIS'. So, I suggest to exclude SYS_CHANGED records from this usercode.
Also note that you didn't sort descending on D_CHANGE, only on milli.
If the DB is Microsoft SQL Server:
- You don't need to use the column
MILLI. It was added for Oracle
- The top statement does respect the order clause, in constrast with rownum on Oracle.
So, this could be one of your sub-queries in the update.
select top 1 D_CHANGE from SYS_CHANGED
where K_TABLE = 31000 and K_1=d.K_DOCUMENT
and OPERATION in ('B', 'A') and USERNAME<>'ADMIN'
order by D_CHANGE desc, MILLI desc
If you are afraid of doing the wrong update, here are some tips, assuming there is already a decent backup:
- Make a duplicate of the DOCUMENTS table before the update
- Do the update within a transaction
SQL Server syntax:
-- Begin transaction
-- Do your update statement
-- Check your update
-- Based on the result, rollback or commit