如何更新 SQL 中的选择性字段(保留一些不变)? [英] How do I update selective fields in SQL (leaving some unchanged)?

查看:39
本文介绍了如何更新 SQL 中的选择性字段(保留一些不变)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新具有两个日期的记录,如果我没有新的值来更新,则保留现有数据不变.

I would like to update a record with two dates, leaving existing data intact if I do not have a new value to update with.

这是一个示例表记录:

id  last_foo    last_bar
--  ----------  ----------
 1  2010-05-30  2010-05-30

以及我正在使用的查询:

And the query I am using:

UPDATE sampledates
   SET last_foo = @LastFoo, 
       last_bar = @LastBar
 WHERE id = @ID;

如果我的可空日期时间 LastFooLastBar 为空,我想保留现有的 SQL 值原样,否则更新.

If my nullable datetimes LastFoo or LastBar are null, I would like to leave the existing SQL value as-is, otherwise update.

例如,假设我正在使用以下值更新此记录(这是 C#,但适用任何语言):

For example, say I am updating this record with the following values (this is C# but any language applies):

DateTime? LastFoo = new DateTime('2010-06-04');
DateTime? LastBar = null;

我希望记录是:

id  last_foo    last_bar
--  ----------  ----------
 1  2010-06-04  2010-05-30

我意识到如果值为空,我可以更改我的查询文本以省略第二列,但我想知道是否有一种方法可以让查询保持原样并指定我不更改指定的列.

I realize I can alter my query text to omit the second column if the value is null, but I wondered if there is a way I can leave the query as-is and specify that I am not changing the column specified.

推荐答案

尝试

UPDATE sampledates
SET last_foo = COALESCE(@LastFoo,last_foo ), 
last_bar = COALESCE(@LastBar,last_bar )
WHERE id = @ID;

这篇关于如何更新 SQL 中的选择性字段(保留一些不变)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆