Will GETUTCDATE() return the same value if used twice in the same statement?

前端 未结 5 2108
迷失自我
迷失自我 2020-11-30 11:12

I have a trigger that automatically sets the CreationDate and ModifiedDate of the given entry to the current UTC time whenever a value is entered. (CreationDate will remain

5条回答
  •  独厮守ぢ
    2020-11-30 11:56

    It will be the same value.

    GETDATE and GETUTCDATE are some of the functions that are evaluated once per query: not per row or column in that query. The optimiser will ensure they are the same because it updates the values at the same time

    Another option is to define a DEFAULT constraints so you can do this and worry less about it.

    UPDATE dbo.MyTable
    SET CreationDate = DEFAULT, ModifiedDate = DEFAULT, ...
    ...
    

    I have tables with similar columns with DEFAULT constraints and never had an issue. This also means I never have to think about what function I use in code.

    Edit:

    I could be wrong: SQL Server: intrigued by GETDATE()

    Or I could be right: Selecting GETDATE() function twice in a select list-- same value for both?

    Article: Conor Cunnigham mentions it the behaviour

    Edit2: I'm demonstratably wrong: see StriplingWarrior's self answer. It's evaluated per column (not per row and not per query)

提交回复
热议问题