MySQL单个更新查询,不更新非空值

时间:2015-01-19 21:00:16

标签: c# mysql mysql-connector

给出一个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);

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

如何更新say,firstname,而不是hash,而不必为每个可能的单个或分组列更新组合编写单独的更新命令字符串?

1 个答案:

答案 0 :(得分:3)

如果您不想更新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