Friday, March 5, 2010

Function to return start of the week

You might wonder how to get the start of the week.
You have a datetime column value and you want to get get the start week of that date
Say for e.g:
today is march 5th 2010 and the week starts from 1st of march 2010 which is Monday
In order to do that create one function and call this function in your store procedure
code

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[fn_startweek]
(@REPORT_DATE DATETIME)
RETURNS varchar(30)
AS
BEGIN
DECLARE @WEEK_BEGINING VARCHAR(10)

DECLARE @WEEK_START_DATE DATETIME, @WEEK_END_DATE DATETIME
--GET THE WEEK START DATE
SELECT @WEEK_START_DATE = @REPORT_DATE - (DATEPART(DW, @REPORT_DATE) - 1)

--GET THE WEEK END DATE
SELECT @WEEK_END_DATE = @REPORT_DATE + (7 - DATEPART(DW, @REPORT_DATE))

return CONVERT(VARCHAR, @WEEK_START_DATE,101)
end


To call this function:

select dbo.fn_startweek ('2010-03-05 14:51:47.840') //pass the datetime value or a.datecolumnStartdate

1 comment:

  1. Great blog!
    Si vous le souhaitez, de revenir et mine de visite: http://albumdeestampillas.blogspot.com
    Merci,

    Pablo de l'Argentine

    ReplyDelete