Creating date in SQL Server 2008

前端 未结 3 1942
天命终不由人
天命终不由人 2021-02-07 01:23

Is there something similar to DATEFROMPARTS(year, month, day) in SQL Server 2008? I want to create a date using the current year and month, but my own day of the mo

3条回答
  •  伪装坚强ぢ
    2021-02-07 01:38

    Using the 3 from your example, you could do this:

    dateadd(dd, 3 -1, dateadd(mm, datediff(mm,0, current_timestamp), 0))
    

    It works by finding the number of months since the epoch date, adding those months back to the epoch date, and then adding the desired number of days to that prior result. It sounds complicated, but it's built on what was the canonical way to truncate dates prior to the Date (not DateTime) type added to Sql Server 2008.

    You're probably going to see other answers here suggesting building date strings. I urge you to avoid suggestions to use strings. Using strings is likely to be much slower, and there are some potential pitfalls with alternative date collations/formats.

提交回复
热议问题