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 确实获得了一个值,因此声誉参数
最佳答案
改变
SET u.Reputation = (u.Reputation + @Reputation)
进入:
SET u.Reputation = COALESCE(u.Reputation,0) + @Reputation
因此 Reputation
字段中的 NULL
在添加 @Reputation
之前更改为 0
。
或者,如果您首先将所有 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 ;
关于c# - SQL更新语句添加一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6606520/