【问题标题】:MySQL Single update query, without updating non-null valuesMySQL 单次更新查询,不更新非空值
【发布时间】:2015-03-17 23:25:07
【问题描述】:

给定一条 SQL 语句:

const string UpdateString = @"UPDATE users SET hash=@new_hash, firstname=@new_firstname, lastname=@new_lastname WHERE id=@id";

然后我加载到一个 MySqlCommand 对象:

var cmd = new MySqlCommand(UpdateString , connection))
cmd.Prepare();
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@new_hash", hash);

如果我不添加所有参数,我会抛出异常。

我怎样才能只更新名字,而不是哈希,而不必为单个或分组列更新的每个可能组合编写一个单独的更新命令字符串?

【问题讨论】:

  • 为什么投反对票?易于单击向下箭头但不键入并留下建设性评论?!于尔根的回答很到位。

标签: c# mysql mysql-connector


【解决方案1】:

如果您不想更新 hash,则使用此查询为该参数添加 null

UPDATE users 
SET hash = case when @new_hash is null then hash else @new_hash end, 
    firstname = @new_firstname, 
    lastname = @new_lastname 
WHERE id = @id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多