How do I update selective fields in SQL (leaving some unchanged)?

你。 提交于 2021-01-27 06:53:44

问题


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.

Here is a sample table record:

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;

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

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;

I would like the record to then be:

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.


回答1:


Try

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



回答2:


You can use COALESCE:

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

In SQL Server you get a minor performance improvement by using ISNULL instead of COALESCE.

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



回答3:


Try this (this is untested, I don't have SSMS available to me right now)

UPDATE sampledates
   SET last_foo = CASE WHEN @LastFoo IS NULL THEN last_foo ELSE @LastFoo END, 
       last_bar = CASE WHEN @LastBar IS NULL THEN last_foo ELSE @LastBar END
  WHERE id = @ID;



回答4:


You could try something like

UPDATE sampledates
SET last_foo = (case when @LastFoo IS NULL then last_foo else @LastFoo end), 
last_bar = (case when @LastBar IS NULL then last_bar else @LastBar end)
WHERE id = @ID;


来源:https://stackoverflow.com/questions/2978008/how-do-i-update-selective-fields-in-sql-leaving-some-unchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!