即使我不希望它发生,列的更新也会发生

时间:2012-06-26 14:47:34

标签: sql sql-server-2005

我有一个案例陈述:

UPDATE
   Answer
SET
   AnswerID = @AnswerID,
   AnsweredBy = CASE WHEN LEN(@AnsweredBy) > 0 THEN @AnsweredBy END

即使@AnsweredByNULL,它仍然会将AnsweredBy列设置为空。

我试图通过这样做来测试null:

 UPDATE
    Answer
 SET
    AnswerID = @AnswerID,
    AnsweredBy = CASE WHEN @AnsweredBy IS NOT NULL THEN @AnsweredBy END

含义除非有值,否则我不想更新answeredby列。

即使在我的C#代码中,我也没有将值传递给我的存储过程:

if (answeredBy.Length > 0)
   cmdSelect.Parameters.Add("@AnsweredBy", SqlDbType.VarChar).Value = answeredBy;

除非有价值。在我的sproc中,我将该列变量默认为null:

@RunoffAnswerID bigint,
@AnswerID varchar(3)=NULL,
@AnsweredBy varchar(50)=NULL,

所以我的问题是如何执行其余的更新,因为如果answeredby中有值,则只有5到10个列,但只更新@AnsweredBy

2 个答案:

答案 0 :(得分:6)

SET AnsweredBy = ISNULL(@AnsweredBy, AnsweredBy)

答案 1 :(得分:2)

UPDATE 
    Answer 
SET 
    AnswerID = @AnswerID, 
    AnsweredBy = CASE WHEN LEN(@AnsweredBy) > 0 THEN @AnsweredBy ELSE AnsweredBy END