TSQL - 使用ORDER BY更新列值,直到找到某个列值

时间:2016-12-02 10:30:03

标签: sql sql-server database tsql sql-query-store

我有这张桌子:

ID - Uniqueidentifier
TYPEDUT_ID - Uniqueidentifer
OPERATION - Integer
ACTIVE - Integer (0/1)
CREATED - DateTime

我想对行ORDER BY CREATED DESC进行排序,并从上到下更新ACTIVE = 0,直到我达到某个操作。

示例数据:

            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

现在,如果我将3000作为我想要的操作,预期结果应如下所示:

                   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

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以使用子查询获得特定操作的最短创建时间。然后,您可以使用该信息来定义要更新的行:

update t
    set active = 0
    where created >= (select max(t2.created)
                      from t t2
                      where operation = @Operation
                     );

编辑:

显然,我向后理解。解决方案是另一种方式:

string line = string.Empty;
for(int i = 0; i < 250 && (line = reader.ReadLine()) != null; i++) {
    // your code
}