Datepart(year, …) vs. Year(…)

后端 未结 2 658
太阳男子
太阳男子 2021-01-04 00:12

What are the advantages of using one over the other in the following:

DATEPART(YEAR, GETDATE())

As opposed to:

YEAR(GETDATE         


        
2条回答
  •  借酒劲吻你
    2021-01-04 00:33

    Actually - using YEAR(..) is preferably for me, since it's considered a deterministic function, so if I use this in a computed column definition

    ALTER TABLE dbo.MyTable
    ADD YearOfDate AS YEAR(SomeDateColumn)
    

    I can make this column persisted (and store it into the table):

    ALTER TABLE dbo.MyTable
    ADD YearOfDate AS YEAR(SomeDateColumn) PERSISTED
    

    This does not work for DATEPART(YEAR, SomeDateColumn) (don't ask me why - just noticed this heuristically).

    The same applies to MONTH(SomeDate) vs. DATEPART(MONTH, SomeDate).

    If you have tables that you need to select from based on the month and year of a date (like SalesDate or something), then having month and years as persisted computed columns (and indexing them) can be a huge performance boost.

提交回复
热议问题