SQL将时间设置为午夜功能

时间:2012-12-12 16:30:33

标签: sql datetime

我有这个功能

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以及查找提供日期的一周结束有什么想法吗?

2 个答案:

答案 0 :(得分: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)))    

答案 1 :(得分:0)

自SQL Server 2005以来,删除时间的最佳方法是强制转换为date数据类型:

select cast(@Date as date)

我建议你让函数返回date而不是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函数也是如此。)