0

我有这个功能

ALTER FUNCTION [General].[GetWeekEnding] 
(
@Date DATETIME
)
RETURNS DATETIME
AS
BEGIN
-- Return the result of the function
RETURN (DATEADD(day, -1 - (DATEPART(dw, @Date) + @@DATEFIRST - 2) % 7, @Date) + 7)
END

我还需要将时间设置为 00:00:00.000 以及找到所提供日期的一周结束有什么想法吗?

4

2 回答 2

1

我使用 UDF 将时间组件添加到日期,例如

CREATE FUNCTION [dbo].[DateTimeAdd] 
( 
      @datepart         date, 
      @timepart         time 
) 
RETURNS datetime2 
AS 
BEGIN 
      RETURN DATEADD(dd, DATEDIFF(dd, 0, @datepart), CAST(@timepart AS datetime2)); 
END

然后在您的情况下,您可以像这样使用它:

SELECT dbo.DateTimeAdd(DATEADD (D, -1 * DatePart (DW, GetDate()) + 7, GetDate()), DATEADD(hh, 0, CAST(DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), -1)  AS TIME)))    
于 2012-12-12T16:52:32.563 回答
0

自 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 函数也是如此。)

于 2012-12-12T18:53:34.417 回答