c# - SQL更新语句添加一个值

标签 c# asp.net sql sql-update

   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/

相关文章:

mysql - 数据库设计 : lots of rows vs lots of tables?

c# datatable select 带日期的语句

c# - Web Api 中简单 GET 查询的长 TTFB

sql - 通过复制现有表的结构来创建表

php - 使用 php 显示 mysql 的所有结果的问题

asp.net - 如何在 SQL Server 存储过程中用逗号分隔(分割)字符串

c# - 如何在 C# 中的 SSH 服务器上运行命令?

c# - 避免 If Else 条件

c# - 将 PNG 图像打印到 Zebra 网络打印机

asp.net - EF4 : AutoDetectChangesEnabled not found