Another variation of start of week function, adapted from this function:http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47307This returns a start of week for a given date and start day of week, offset +/- by a number of weeks.See the code below for samples of how to call it, and sample results.drop function dbo.F_START_OF_WEEK_INCREMENTgocreate function dbo.F_START_OF_WEEK_INCREMENT( @DATE datetime, @WEEK_START_DAY varchar(10) = 'sunday', @WEEK_INCREMENT int = 0 )/*Find the fisrt date on or before @DATE + @WEEK_INCREMENTthat matches day of week of @WEEK_START_DAY.*/returns datetimeasbeginselect @DATE = dateadd(day,@WEEK_INCREMENT*7,@DATE)declare @WEEK_START_DAY_NUM intselect @WEEK_START_DAY_NUM = case lower(@WEEK_START_DAY) when 'sunday' then 1 when 'monday' then 2 when 'tuesday' then 3 when 'wednesday' then 4 when 'thursday' then 5 when 'friday' then 6 when 'saturday' then 7 enddeclare @START_OF_WEEK_DATE datetimedeclare @FIRST_BOW datetime-- Check for valid day of weekif @WEEK_START_DAY_NUM between 1 and 7 begin -- Find first day on or after 1753/1/1 (-53690) -- matching day of week of @WEEK_START_DAY_NUM -- 1753/1/1 is earliest possible SQL Server date. select @FIRST_BOW = convert(datetime,-53690+((@WEEK_START_DAY_NUM+5)%7)) -- Verify beginning of week not before 1753/1/1 if @DATE >= @FIRST_BOW begin select @START_OF_WEEK_DATE = dateadd(dd,(datediff(dd,@FIRST_BOW,@DATE)/7)*7,@FIRST_BOW) end endreturn @START_OF_WEEK_DATEendgoset nocount ondeclare @DATE datetimedeclare @WEEK_INCREMENT intselect @DATE = '2006/1/7'select @WEEK_INCREMENT = 1select [Def]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,default,default)select [Sun]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'sunday',@WEEK_INCREMENT)select [Mon]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'monday',@WEEK_INCREMENT)select [Tue]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'tuesday',@WEEK_INCREMENT)select [Wed]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'wednesday',@WEEK_INCREMENT)select [Thu]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'thursday',@WEEK_INCREMENT)select [Fri]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'friday',@WEEK_INCREMENT)select [Sat]=dbo.F_START_OF_WEEK_INCREMENT(@DATE,'saturday',@WEEK_INCREMENT)Results:Def------------------------2006-01-01 00:00:00.000Sun------------------------2006-01-08 00:00:00.000Mon------------------------2006-01-09 00:00:00.000Tue------------------------2006-01-10 00:00:00.000Wed------------------------2006-01-11 00:00:00.000Thu------------------------2006-01-12 00:00:00.000Fri------------------------2006-01-13 00:00:00.000Sat------------------------2006-01-14 00:00:00.000
CODO ERGO SUM