需要函数给出第一天的第一天的DateTime给出第一天的第一天的天数

时间:2014-12-21 00:20:25

标签: sql-server

对于很多人来说,工作周的第一天是星期一,但我们可以说它是另一天,周三说。

你能帮我创建一个函数(SQL Server 2012),它返回第一天的日期:

  1. 本周
  2. 下周
  3. 上周
  4. 这是一个函数,我们给出一个日期,类型(当前,下一个,最后一个),FirstDay(0,1,2,3,4,5,6),并返回当前或下一个的第一天的日期时间或一周的最后一天取决于类型。

    创建功能[dbo]。[GetStartofWeek] (
        @FirstDay int,     @type VARCHAR(10),     @day DATETime ) 退货日期 如 BEGIN

    由于

1 个答案:

答案 0 :(得分:2)

我相信这会给你你想要的日期:

create function [dbo].[GetStartofWeek] 
(
    @firstDay int, 
    @type varchar(10), 
    @day date
) 
returns date as
begin

-- use datediff/dateadd to get the date of sunday for the week of the given @day (-1 casts as Sunday 1899-12-31)
declare @sundayOfWeek date = dateadd(week, datediff(week, -1, @day), -1)

-- @firstDay is 0 to 6, 0 representing Sunday
declare @firstDayOfWeek date = dateadd(day, @firstDay, @sundayOfWeek)

-- add or subtract a week if necessary
set @type = upper(@type)

if @type = 'LAST'
    set @firstDayOfWeek = dateadd(week, -1, @firstDayOfWeek)
else if @type = 'NEXT'
    set @firstDayOfWeek = dateadd(week, 1, @firstDayOfWeek)

return @firstDayOfWeek
end
go

使用以下输入进行测试:

select [dbo].[GetStartofWeek](0, 'Last',    '2014-12-14')   -- 2014-12-07   
select [dbo].[GetStartofWeek](3, 'Last',    '2014-12-14')   -- 2014-12-10   
select [dbo].[GetStartofWeek](6, 'Last',    '2014-12-14')   -- 2014-12-13   
select [dbo].[GetStartofWeek](0, 'Current', '2014-12-17')   -- 2014-12-14   
select [dbo].[GetStartofWeek](3, 'Current', '2014-12-17')   -- 2014-12-17
select [dbo].[GetStartofWeek](6, 'Current', '2014-12-17')   -- 2014-12-20
select [dbo].[GetStartofWeek](0, 'Next',    '2014-12-20')   -- 2014-12-21
select [dbo].[GetStartofWeek](3, 'Next',    '2014-12-20')   -- 2014-12-24
select [dbo].[GetStartofWeek](6, 'Next',    '2014-12-20')   -- 2014-12-27

一个建议是使用一周偏移而不是'Last'/'Current'/'Next',这样更清洁,更灵活:

alter function [dbo].[GetStartofWeek] 
(
    @firstDay int, 
    @weekOffset int, 
    @day date
) 
returns date as
begin

-- use datediff/dateadd to get the date of sunday for the week of the given @day (-1 casts as Sunday 1899-12-31)
declare @sundayOfWeek date = dateadd(week, datediff(week, -1, @day), -1)

-- @firstDay is 0 to 6, 0 representing Sunday
declare @firstDayOfWeek date = dateadd(day, @firstDay, @sundayOfWeek)

-- add or subtract weeks if necessary
if @weekOffset <> 0
begin
    set @firstDayOfWeek = dateadd(week, @weekOffset, @firstDayOfWeek)
end

return @firstDayOfWeek
end
go