由于空值,用Case语句更新失败

时间:2019-02-19 13:48:12

标签: sql sql-server case

我在表中有一列,我想将当前值与另一个用于特定条目的值交换。显然我没有把它留空时,我得到了一个没有空约束。

UPDATE bet.betEntry
SET direction= 
            CASE 
                WHEN (direction = '599065F7-96A9-4DF5-8577-2203BE9AA2E0') THEN  'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                WHEN (direction = 'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5') THEN '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
         END    
FROM bet.betEntry be JOIN bet.fixture f ON  be.fixtureId = f.fixtureId
WHERE f.fixtureDate > '2019-01-12 13:29:00.000'

2 个答案:

答案 0 :(得分:6)

添加一个where子句:

UPDATE bet.betEntry
    SET direction = (CASE WHEN direction = '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
                          THEN  'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                          WHEN direction = 'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                          THEN '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
                     END)   
FROM bet.betEntry be JOIN
     bet.fixture f
     ON  be.fixtureId = f.fixtureId
WHERE f.fixtureDate > '2019-01-12 13:29:00.000' AND
      direction IN ('599065F7-96A9-4DF5-8577-2203BE9AA2E0', '599065F7-96A9-4DF5-8577-2203BE9AA2E0');

您也可以使用ELSE direction解决此问题。但是,这样做并不好,因为它尝试更新不需要更新的行。

答案 1 :(得分:1)

您的ELSE引起了问题,您可以添加where子句(direction IN ('599065F7-96A9-4DF5-8577-2203BE9AA2E0', '599065F7-96A9-4DF5-8577-2203BE9AA2E0'))或添加elseELSE direction):

UPDATE bet.betEntry
     SET direction = (CASE WHEN direction = '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
                           THEN 'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                           WHEN direction = 'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                           THEN '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
                           ELSE direction             
                      END)    
FROM bet.betEntry be JOIN
     bet.fixture f
     ON  be.fixtureId = f.fixtureId
WHERE f.fixtureDate > '2019-01-12 13:29:00.000';