简体   繁体   English

更新表与子查询中的表相同

[英]Updating table is the same as the table in the sub-query

UPDATE MyTable SET Status = (SELECT CASE WHEN COUNT(*) > 0
                            THEN 0          
                            ELSE 1
                            END 
                    FROM MyTable 
                    WHERE Status = 1 )
WHERE RowNumber BETWEEN 1 AND 5
ORDER BY RowNumber

What I want to do is there will be only one row in MyTable with Status = 1. While I update RowNumber 1 to 5, if there has been an existing record with Status = 1, those RowNumber 1 to 5 will be updated with 0. Otherwise, only RowNumber 1 will be updated to 0 and RowNumber 2 to 5 will be set 0. 我想做的是MyTable中只有状态为1的一行。当我将行号1更新为5时,如果存在状态为1的现有记录,则行号1至5的行将被更新为0。否则,仅行号1将更新为0,行号2至5将设置为0。

But aforementioned query is not working. 但上述查询无法正常工作。 I guess sub-query is run before the whole query and the result from the sub-query is static which means not giving new result as one record after another is being updated. 我猜子查询在整个查询之前运行,并且子查询的结果是静态的,这意味着在更新另一个记录时不会给出新结果。

With this query, if there is no row in the table with Status = 1 then all RowNumber 1 to 5 are updated with Status = 1. This is not what I am expecting. 通过此查询,如果表中没有状态= 1的行,则所有行号1至5都将更新为状态=1。这不是我所期望的。

Not sure if I understand fully what you're after - but it sounds like you need to add a nested case statement in the else clause of your original case. 不知道我是否完全了解您的要求-听起来您需要在原始案例的else子句中添加一个嵌套的case语句。 See the code below: 请参见下面的代码:

UPDATE MyTable SET Status = (SELECT CASE WHEN COUNT(*) > 0
                        THEN 0          
                        ELSE CASE WHEN RowNumber = 1 THEN 1
                             ELSE 0 END
                        END 
                FROM MyTable 
                WHERE Status = 1 )
WHERE RowNumber BETWEEN 1 AND 5
ORDER BY RowNumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM