2011-07-07 85 views
1
public void InsertUserReputation() 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("UPDATE u "); 
    sb.Append(" SET u.Reputation = (u.Reputation + @Reputation)");//Problem is here u.Reputation is "Null" not 0... I think i need some if statement to check if it is a null and then update it to 0 and then add..what do you think? 
    sb.Append(" FROM Users u"); 
    sb.Append(" INNER JOIN Comments c ON c.UsersID = u.UsersID"); 
    sb.Append(" WHERE c.CommentsID = @CommentsID"); 

    using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString)) 
    { 
     SqlCommand cmd = new SqlCommand(sb.ToString(), conn); 
     cmd.Parameters.Add("@Reputation", SqlDbType.Int).Value = 5; 
     cmd.Parameters.Add("@CommentsID", SqlDbType.Int).Value = commentID; 
     conn.Open(); 
     cmd.ExecuteNonQuery(); 
    } 
} 

我想给用户添加一个信誉给5分的用户,他留在线程中的评论..但它无法更新为什么?/ ... commentID确实得到一个价值等信誉参数SQL更新语句添加一个值

+0

(你不需要为该语句使用StringBuilder,顺便说一句 - 这只是增加了一小部分开销,但更重要的是:它使得代码不必要的复杂) –

+3

是'u.Reputation' null的任何机会? –

+0

你得到的错误是什么?或者它运行,但没有错误?请详细说明。 – Cortright

回答

1
sb.Append(" SET Reputation = (u.Reputation + @Reputation)"); 

编辑:我错过了你关于u的原始笔记,可能是空值。尝试下:

sb.Append(" SET Reputation = (isnull(u.Reputation,0) + @Reputation)"); 
+0

dammit stil不工作..我不知道whyh – WithFlyingColors

+0

编辑我的答案。其实ypercube的答案应该给出相同的结果。 – Arvo

3

变化

SET u.Reputation = (u.Reputation + @Reputation) 

到:

SET u.Reputation = COALESCE(u.Reputation,0) + @Reputation 

所以NULL S IN Reputation场均变为0加入@Reputation之前。


或者,你可以保持你的代码,如果你第一次将所有NULL0,然后用语句ALTER TABLE使现场NOT NULL。执行以下,一旦:

UPDATE Users 
SET Reputation = 0 
WHERE Reputation IS NULL ; 

ALTER TABLE Users 
ALTER COLUMN Reputation NOT NULL DEFAULT 0 ; 
0

你也可以改变

SET u.Reputation = (u.Reputation + @Reputation) 

SET u.Reputation = COALESCE(u.Reputation + @Reputation, @Reputation, 0) 

但所有现有的答案很好满足您的需求

唯一受益以上提供的是,在@Reputation也是NULL的情况下,它仍然有效。