gpt4 book ai didi

sql-server - 负数与 MONTH 日期部分一起使用时的 DATEADD 问题

转载 作者:行者123 更新时间:2023-12-02 03:16:41 26 4
gpt4 key购买 nike

来自DATEADD文档:

If datepart is month and the date month has more days than the return month and the date day does not exist in the return month, the last day of the return month is returned. For example, September has 30 days; therefore, the two following statements return 2006-09-30 00:00:00.000:

SELECT DATEADD(month, 1, '2006-08-30');

SELECT DATEADD(month, 1, '2006-08-31');

SQL Server 知道 2016-03 的最后一天是 312016-04 的最后一天30:

SELECT DAY(EOMONTH('2016-03-01')) -- 31
SELECT DAY(EOMONTH('2016-04-01')) -- 30

那么为什么会这样:

SELECT DATEADD(MONTH, -1, '2016-04-30')

返回 2016-03-30 00:00:00.000 而不是 2016-03-31 00:00:00.000?

此外,如果我有以下内容:

SELECT  DATEADD(MONTH, -1, '2016-03-31')

它正确返回 2016-02-29 00:00:00.000

最佳答案

正如其他评论所说,如果上个月存在该月的某天,DATEADD 将使用它,而不是假设您想要“该月的最后一天”。

如果您确实想要“本月的最后一天”,则必须增加一些逻辑,例如:

DECLARE @date DATETIME = '30 April 2016'
SELECT CASE WHEN DATEDIFF(MONTH, @date, DATEADD(DAY, 1, @date)) = 1 THEN DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @date), 0))
ELSE DATEADD(MONTH, -1, @date)
END

这将假设如果它是该月的最后一天,您需要上个月的最后一天,而不是明确的 28 日、29 日或 30 日。

关于sql-server - 负数与 MONTH 日期部分一起使用时的 DATEADD 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36618563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com