Updating two rows in the same column with one string query sql.

huangapple go评论65阅读模式
英文:

Updating two rows in the same column with one string query sql

问题

我试图在同一张表中将值为1的活动行在激活另一行时更改为0(并将新行从0更改为1)。

UPDATE SpecialTBL
SET Active = 0
WHERE Active = 1 AND SpecID = @SpecID;

UPDATE SpecialTBL
SET Active = 1
WHERE Active = 0 AND SpecID = @SpecID;

这两个语句单独运行正常,但无法嵌套它们在一起。

英文:

I'm trying to make an active row with value 1 change to 0 when activating another row (and turning the new row from 0 to 1) in the same table.

UPDATE SpecialTBL 
SET Active = 0 
WHERE Active = 1 AND SpecID = @SpecID;

UPDATE SpecialTBL 
SET Active = 1 
WHERE Active = 0 AND SpecID = @SpecID;

Both these works separately but I can't nestle them together.

答案1

得分: 3

以下是翻译好的部分:

你只需使用算术操作:

    UPDATE SpecialTBL 
    SET Active = 1 - Active 
    WHERE SpecID = @SpecID

如果可能存在除01以外的其他活动值,则我们需要另一个过滤条件:

    UPDATE SpecialTBL 
    SET Active = 1 - Active 
    WHERE SpecID = @SpecID AND Active in (0,1)

否则,使用 CASE 表达式更常规:

    UPDATE SpecialTBL 
    SET Active = CASE Active WHEN 1 THEN 0 ELSE 1 END
    WHERE SpecID = @SpecID AND Active in (0,1)
英文:

You can just use arithmetic:

UPDATE SpecialTBL 
SET Active = 1 - Active 
WHERE SpecID = @SpecID

If there may be other active values than 0 and 1, then we would need another filtering condition:

UPDATE SpecialTBL 
SET Active = 1 - Active 
WHERE SpecID = @SpecID AND Active in (0,1)

Else, a case expression is more conventional:

UPDATE SpecialTBL 
SET Active = CASE Active WHEN 1 THEN 0 ELSE 1 END
WHERE SpecID = @SpecID AND Active in (0,1)

答案2

得分: 1

你可以使用 ~ 操作符来对 BIT 数据类型进行按位取反。

UPDATE SpecialTBL SET Active = ~Active WHERE SpecID = @SpecID

英文:

You could use the ~ bitwise NOT for BIT data type.

UPDATE SpecialTBL SET Active = ~Active
WHERE SpecID = @SpecID

huangapple
  • 本文由 发表于 2023年3月31日 04:07:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定