如何使用一个SQL Update命令设置启动和修改日期?

时间:2015-04-26 07:37:53

标签: sql-server sql-server-2012

我有一个简单的SQL Server表:

CREATE TABLE [dbo].[UserTest] 
(
    [UserTestId]    INT      IDENTITY (1, 1) NOT NULL,
    [UserId]        INT      NOT NULL,
    [ModifiedDate]  DATETIME NULL,
    [StartedDate]   DATETIME NULL
);

我将修改日期设置为:

UPDATE UserTest
SET    ModifiedDate = @ModifiedDate
WHERE  UserTestId = @UserTestId
AND    UserId = @UserId

但如果StartedDate@ModifiedDate,我是否可以将同一SQL中的StartedDate设置为NULL

4 个答案:

答案 0 :(得分:4)

如果它不为null,您可以使用COALESCE语句将StartedDate设置为自身,如果不为null,则可以使用@ModifiedDate。

$(window).height()

答案 1 :(得分:3)

您也可以使用Case语句。

UPDATE UserTest
SET    ModifiedDate = @ModifiedDate,
       StartedDate = CASE WHEN StartedDate IS NULL THEN @ModifiedDate ELSE StartedDate END
WHERE  UserTestId = @UserTestId
AND    UserId = @UserId

答案 2 :(得分:2)

由于您使用的是SQL Server 2012,因此您还可以使用IIF

UPDATE UserTest
SET    ModifiedDate = @ModifiedDate,
       StartedDate = IIF(StartedDate IS NULL, @ModifiedDate, StartedDate)
WHERE  UserTestId = @UserTestId
AND    UserId = @UserId

答案 3 :(得分:1)

您可以选择使用ISNULL

UPDATE UserTest
SET    ModifiedDate = @ModifiedDate,
       StartedDate = ISNULL(StartedDate, @ModifiedDate)
WHERE  UserTestId = @UserTestId
       AND    UserId = @UserId
相关问题