I have this table:
ID - Uniqueidentifier
TYPEDUT_ID - Uniqueidentifer
OPERATION - Integer
ACTIVE - Integer (0/1)
CREATED - DateTime
I want to sort the rows ORDER BY CREATED DESC
and update ACTIVE = 0
from the top to bottom till I reach a certain OPERATION.
Sample data:
ID TYPEDUT_ID OPERATION ACTIVE CREATED
ADFFC7CB-C938-448B-BF15-019C31434AFD CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2000 1 2016-09-06 13:06:29.333
CF7E2375-EC6E-416F-99E6-15213BD829D8 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 3000 1 2016-09-06 13:01:47.657
31189043-8B7E-4DCC-8EAC-62AD5EDB32E2 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2000 1 2016-09-06 13:10:07.720
E473B887-65DB-40FA-94D9-697F20E787B9 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2300 1 2016-09-06 13:30:41.227
1DD2C120-7859-4868-9C71-83F6BC3F7488 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 3100 1 2016-09-06 14:40:46.087
B27283A8-43DD-468E-95CB-99DD1BC95321 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2100 1 2016-09-06 13:23:34.883
103899E9-33B1-4FCA-AA1B-A51040B35FBD CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2400 1 2016-09-06 14:03:21.830
Now if I put 3000 as my desired OPERATION the expected result should look like this:
ID TYPEDUT_ID OPERATION ACTIVE CREATED
1DD2C120-7859-4868-9C71-83F6BC3F7488 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 3100 0 2016-09-06 14:40:46.087
103899E9-33B1-4FCA-AA1B-A51040B35FBD CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2400 0 2016-09-06 14:03:21.830
E473B887-65DB-40FA-94D9-697F20E787B9 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2300 0 2016-09-06 13:30:41.227
B27283A8-43DD-468E-95CB-99DD1BC95321 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2100 0 2016-09-06 13:23:34.883
31189043-8B7E-4DCC-8EAC-62AD5EDB32E2 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2000 0 2016-09-06 13:10:07.720
ADFFC7CB-C938-448B-BF15-019C31434AFD CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 2000 0 2016-09-06 13:06:29.333
CF7E2375-EC6E-416F-99E6-15213BD829D8 CC055EBE-2655-4B2F-B6C2-BF9BCE46941B 3000 1 2016-09-06 13:01:47.657
If I understand correctly, you can get the minimum created time for a particular operation using a subquery. You can then use that information to define the rows to be updated:
update t
set active = 0
where created <= (select min(t2.created)
from t t2
where operation = @Operation
);
EDIT:
Apparently, I understand backwards. The solution is the other way:
update t
set active = 0
where created >= (select max(t2.created)
from t t2
where operation = @Operation
);