自 SQL Server 2005 以来,删除时间的最佳方法是强制转换为date
数据类型:
select cast(@Date as date)
我建议你让你的函数返回 adate
而不是 a datetime
。
要获得一周结束,您需要一个查找表来将一周中的日期映射到整数。您可以使用datepart
. 但是,这取决于系统设置。这是一个函数:
Create FUNCTION [GetWeekEnding] (
@Date DATETIME,
@WeekEndingDOW varchar(10)
)
RETURNS DATE
AS
BEGIN
-- Return the result of the function
declare @newdate datetime;
with lookup as (
select 'Sunday' as dow, 0 as daynum union all
select 'Monday' as dow, 1 as daynum union all
select 'Tuesday' as dow, 2 as daynum union all
select 'Wednesday' as dow, 3 as daynum union all
select 'Thursday' as dow, 4 as daynum union all
select 'Friday' as dow, 5 as daynum union all
select 'Saturday' as dow, 6 as daynum
)
select @newdate = @Date - (select daynum from lookup where datename(dw, @date) = dow) + (select daynum from lookup where @WeekEndingDOW = dow);
select @newdate = (case when @newdate < @date then @newdate + 7 else @newdate end)
RETURN cast(@newdate as date)
END;
请注意,此函数确实在datetime
内部使用。出于某种我无法理解的原因,当@date 是日期时间时,您可以说“@date + 1”来表示“在日期值上加一天”。但是,当 @date 是日期时,这不起作用。(dateadd 函数也是如此。)