4

我想用两个日期更新记录,如果我没有要更新的新值,则保持现有数据不变。

这是一个示例表记录:

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

我正在使用的查询:

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

如果我的可空日期 LastFoo时间或LastBar为空,我想保持现有 SQL 值不变,否则更新。

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

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

我希望记录是:

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

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

4

4 回答 4

9

尝试

UPDATE sampledates
SET last_foo = COALESCE(@LastFoo,last_foo ), 
last_bar = COALESCE(@LastBar,last_bar )
WHERE id = @ID;
于 2010-06-04T21:45:43.177 回答
6

您可以使用COALESCE

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

在 SQL Server 中,通过使用ISNULL而不是 COALESCE ,您可以获得较小的性能改进。

UPDATE sampledates
SET last_foo = ISNULL(@LastFoo, last_foo),
    last_bar = ISNULL(@LastBar, last_bar)
WHERE id = @ID;
于 2010-06-04T21:46:08.717 回答
2

试试这个(这是未经测试的,我现在没有可用的 SSMS)

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;
于 2010-06-04T21:46:53.720 回答
1

你可以尝试类似的东西

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;
于 2010-06-04T21:48:38.117 回答