多年来,我已经多次使用@Portman的答案作为地板日期的参考,并将其工作移至您可能会发现有用的功能中。
我对它的性能不做任何声明,而只是将其作为工具提供给用户。
我要求,如果您决定赞成这个答案,请也赞成@Portman的答案,因为我的代码是他的衍生作品。
IF OBJECT_ID('fn_FloorDate') IS NOT NULL DROP FUNCTION fn_FloorDate
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_FloorDate] (
@Date DATETIME = NULL,
@DatePart VARCHAR(6) = 'day'
)
RETURNS DATETIME
AS
BEGIN
IF (@Date IS NULL)
SET @Date = GETDATE();
RETURN
CASE
WHEN LOWER(@DatePart) = 'year' THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0)
WHEN LOWER(@DatePart) = 'month' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0)
WHEN LOWER(@DatePart) = 'day' THEN DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)
WHEN LOWER(@DatePart) = 'hour' THEN DATEADD(HOUR, DATEDIFF(HOUR, 0, @Date), 0)
WHEN LOWER(@DatePart) = 'minute' THEN DATEADD(MINUTE, DATEDIFF(MINUTE, 0, @Date), 0)
WHEN LOWER(@DatePart) = 'second' THEN DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', @Date), '2000-01-01')
ELSE DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)
END;
END
用法:
DECLARE @date DATETIME;
SET @date = '2008-09-17 12:56:53.430';
SELECT
@date AS [Now],
dbo.fn_FloorDate(@date, 'year') AS [Year],
dbo.fn_FloorDate(default, default) AS [NoParams],
dbo.fn_FloorDate(@date, default) AS [ShouldBeDay],
dbo.fn_FloorDate(@date, 'month') AS [Month],
dbo.fn_FloorDate(@date, 'day') AS [Day],
dbo.fn_FloorDate(@date, 'hour') AS [Hour],
dbo.fn_FloorDate(@date, 'minute') AS [Minute],
dbo.fn_FloorDate(@date, 'second') AS [Second];