简体   繁体   中英

Sql update command with optional parameters?

I am inserting circa 500 000 objects into database, where many of them are same (have same primary key representation in database), but other fields might be different so I am using approach "update - if no rows affected - insert". The problem is that sometimes an object has some field set to null (unreadable from file) and is already in database with some value set, thus I update it to null = erase it .) How would implement scenario, that you would update only fields that are not null?

Here is a simple example of how I am doing it now:

private const string UpdateKun = "UPDATE pde.Kun SET Jmeno=@Jmeno WHERE Licence=@Licence";
private const string InsertKun = "INSERT INTO pde.Kun ([Licence], [Jmeno], [VykonnostniStupen]) VALUES (@Licence, @Jmeno, @VykonnostniStupen)";

var cmd = new SqlCommand(UpdateKun, conn, tran);
cmd.Parameters.AddWithValue("@Licence", kun.Licence);
cmd.Parameters.AddWithValue("@Jmeno", kun.Jmeno);
RepairNulls(cmd.Parameters);
if (cmd.ExecuteNonQuery() > 0) return;

cmd = new SqlCommand(InsertKun, conn, tran);
cmd.Parameters.AddWithValue("@Licence", kun.Licence);
cmd.Parameters.AddWithValue("@Jmeno", kun.Jmeno);
cmd.Parameters.AddWithValue("@VykonnostniStupen", 0);
RepairNulls(cmd.Parameters);
cmd.ExecuteNonQuery();


private void RepairNulls(SqlParameterCollection col)
    {
        foreach (SqlParameter param in col.Cast<SqlParameter>().Where(param =>  param.Value == null))
        {
            param.Value = DBNull.Value;
        }
    }

Change the Update to:

UPDATE pde.Kun 
SET Jmeno=@Jmeno 
WHERE Licence=@Licence
  AND @Jmeno IS NOT NULL

If you have more than one columns to update:

UPDATE pde.Kun 
SET Jmeno = COALESCE(@Jmeno, Jmeno)
  , ColumnB = COALESCE(@ColumnB, ColumnB) 
WHERE Licence=@Licence

Don't update the database just for checking if the row exists

SELECT COUNT(*) FROM pde.Kun WHERE Licence=@Licence

and just check if the returned value is greater then 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM