SQL查询以查找该月的最后一天

2021-12-10 00:00:00 datetime date sql-server-2005 sql-server

我需要按以下格式查找一个月的最后一天:

I need to find the last day of a month in the following format:

"2013-05-31 00:00:00:000"

请大家帮忙.

推荐答案

试试这个 -

CREATE FUNCTION [dbo].[udf_GetLastDayOfMonth] 
(
    @Date DATETIME
)
RETURNS DATETIME
AS
BEGIN

    RETURN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @Date) + 1, 0))

END

查询:

DECLARE @date DATETIME
SELECT @date = '2013-05-31 15:04:10.027'

SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date) + 1, 0))

输出:

-----------------------
2013-05-31 00:00:00.000

相关文章