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确实获得了一个值,因此信誉参数
答案 0 :(得分:3)
更改
SET u.Reputation = (u.Reputation + @Reputation)
成:
SET u.Reputation = COALESCE(u.Reputation,0) + @Reputation
所以NULL
字段中的Reputation
在添加0
之前已更改为@Reputation
。
或者,如果您首先将所有NULL
值设置为0
,然后使用语句ALTER TABLE创建字段NOT NULL
,则可以保留代码。执行以下操作,一次:
UPDATE Users
SET Reputation = 0
WHERE Reputation IS NULL ;
ALTER TABLE Users
ALTER COLUMN Reputation NOT NULL DEFAULT 0 ;
答案 1 :(得分:1)
sb.Append(" SET Reputation = (u.Reputation + @Reputation)");
编辑:我错过了关于你的原始笔记。可能是空的。尝试下一步:
sb.Append(" SET Reputation = (isnull(u.Reputation,0) + @Reputation)");
答案 2 :(得分:0)
你也可以改变
SET u.Reputation = (u.Reputation + @Reputation)
到
SET u.Reputation = COALESCE(u.Reputation + @Reputation, @Reputation, 0)
但所有现有答案都能很好地满足您的需求
上面提供的唯一好处是,如果@Reputation也是NULL,它仍然有效。