且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在SQL Server 2008中创建日期

更新时间:2022-11-01 13:10:35

使用您的示例中的 3 可以这样做:

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

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

它可以通过查找纪元日期后的月份数,将这些月份添加到纪元日期,然后添加所需数量几天之前的结果。这听起来很复杂,但是它建立在在SQL Server 2008中添加的 Date (而不是DateTime)类型之前截断日期的规范。

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 that technique. Using strings is likely to be much slower, and there are some potential pitfalls with alternative date collations/formats.