不确定如何应用isNull(x,0)

时间:2012-03-04 04:28:39

标签: sql-server

在Microsoft SQL Server 2008中,我想执行以下操作:

UPDATE dbo.Test SET
Earned=(
SELECT Points
FROM dbo.Answer
WHERE AnswerID = Guess_AnswerID
AND Correct=1
)

问题是当correct = 0时,select为null,而Earned需要为0而不是null。

3 个答案:

答案 0 :(得分:2)

在任何2个表达式周围添加IsNull。在这种情况下,您也可以使用Coalesce。

UPDATE dbo.Test SET
Earned=IsNull((
    SELECT Points
    FROM dbo.Answer
    WHERE AnswerID = Guess_AnswerID
    AND Correct=1
), 0)

您可能还希望将每个匹配答案的所有要点相加。如果是这种情况,则需要将其设为Sum(Points)而不仅仅是Points。

UPDATE dbo.Test SET
Earned=IsNull((
    SELECT Sum(Points)
    FROM dbo.Answer
    WHERE AnswerID = Guess_AnswerID
    AND Correct=1
), 0)

答案 1 :(得分:0)

如果正确= 0

,这将有效
 UPDATE dbo.Test SET
Earned=(
SELECT isnull(Points,0)
FROM dbo.Answer
WHERE AnswerID = Guess_AnswerID
)

答案 2 :(得分:0)

update t
set Earned=case a.Correct when 1 then a.Points else 0 end
from dbo.Test t
inner join dbo.Answer a on a.AnswerID = Guess_AnswerID