Search

Monday, January 14, 2013

Get First and last day of week

Use below function to get the First day of week


CREATE FUNCTION Week1stDay (@DateInput DateTime)
-- Add the parameters for the function here

RETURNS DateTime
AS
BEGIN
DECLARE @Result DateTime

-- Add the T-SQL statements to compute the return value here
-- 1 -> Sunday, 7 -> Saturday
SELECT @Result = DATEADD(DAY, 1- DATEPART(DW, @DateInput), @DateInput)
RETURN @Result
END

Use below function to get the Last day of week

CREATE FUNCTION WeekLastDay (@DateInput DateTime)

-- Add the parameters for the function here

RETURNS DateTime
AS
BEGIN
DECLARE @Result DateTime
-- Add the T-SQL statements to compute the return value here
-- 1 -> Sunday, 7 -> Saturday
SELECT @Result = DATEADD(DAY, 7- DATEPART(DW, @DateInput), @DateInput)
RETURN @Result
END

Run below script to get the values from function:


SELECT dbo.Week1stDay(GETDATE()) AS StartDate
SELECT dbo.WeekLastDay(GETDATE()) AS EndDate

No comments:

Post a Comment