Search This Blog

Year as Input Parameter Returning First date ,Last Date and Number of Weeks in a Year in SQL

Year as Input Parameter Returning First date ,Last Date and Number of Weeks in a Year in SQL

Today One of Developer asked me that Passing year as Input Parameter can Return me the first date,Lastdate and No. of Weeks of that year So I told him yes it is possible and it is quite simple 
His requirement was through stored Procedure.
So I answered him in same way 
Below is the Script

--Below Procedure will take take year as Input 

create procedure CalculateDate
@Date nvarchar(50)
as
select cast(@Date as datetime)as firstdateofyear, dateadd(dd,-1,dateadd(yy,1,cast(@Date as datetime)))as LastDateofYear
,DATEPART(wk,dateadd(dd,-1,dateadd(yy,1,cast(@Date as datetime))))NoofWeeks

--Execute Procedure to view Result 
CalculateDate '2013'

Output

firstdateofyear                          LastDateofYear                NoofWeeks
2013-01-01 00:00:00.000 2013-12-31 00:00:00.000             53

--Query to Return First Date of Year
select CONVERT(Datetime ,'2012')as firstdateofYear

--Query to Return last Date of Year
select dateadd(dd,-1,dateadd(yy,1,cast('2012' as datetime)))as LastDateofYear

--Query to Return No. of Weeks
select DATEPART(wk,dateadd(dd,-1,dateadd(yy,1,cast('2012' as datetime))))NoofWeeks

No comments:

Post a Comment