NOT NOT NULL时将多行更新为NULL

时间:2018-11-23 12:23:44

标签: sql sql-server

使用SQL Server 2012-我正在尝试将列更新为NULL,其中该列中有一个值并满足其他条件,但是我总是遇到错误:

  

子查询返回多个值。如果子查询后跟=,!,则不允许这样做。 =,<,<=,> Or> =或用作表达式。

这是我到目前为止尝试过的:

UPDATE tblUsers
SET MobilePhoneNumber = CASE WHEN MobilePhoneNumber IS NOT NULL THEN NULL
                             ELSE MobilePhoneNumber
                        END
WHERE IsDisabled = 1
  AND ValidTo IS NOT NULL
  AND Id IN (SELECT Id FROM tblUsers
             WHERE IsDisabled = 1 AND ValidTo IS NOT NULL)

UPDATE tmp
SET MobilePhoneNumber = NULL
FROM tblUsers tmp
    INNER JOIN tblUsers tu ON tmp.Id = tu.Id
WHERE tmp.IsDisabled = 1 AND tmp.ValidTo IS NOT NULL
    AND tmp.MobilePhoneNumber IS NOT NULL

请咨询。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下操作

 UPDATE tblUsers 
 SET MobilePhoneNumber = null
  WHERE  
  Id IN (SELECT Id FROM tblUsers WHERE IsDisabled = 1 AND ValidTo IS NOT NULL)
  and MobilePhoneNumber is not null