how to calculate number of days in year in sql ser

2019-08-12 08:55发布

I want to calculate the number of days in year in SQL server 2008 management studio.

For Example:

  • 2016 : 366
  • 2014 : 365

3条回答
贪生不怕死
2楼-- · 2019-08-12 09:06

Try this...

create function fn(@year varchar(20))
returns int
as
begin   
declare @a int
select @a =DATEPART(dy,@year +'1231')
return @a
end

select dbo.fn('2014')--365
select dbo.fn('2016')--366

DEMO Fiddle

查看更多
女痞
3楼-- · 2019-08-12 09:19

You can try:

  declare @y int;
  set @y = 2014;

  SELECT DATEDIFF(day,  cast(@y as char(4)),  cast(@y+1 as char(4))) Days

Result:

Days
365

2Version by comment:

 declare @y int;
 set @y = 2014;

 SELECT DATEDIFF(day,  cast(cast(@y as char(4)) as date),  cast(cast(@y+1 as char(4)) as date)) DaysCnt
查看更多
神经病院院长
4楼-- · 2019-08-12 09:26

This also works:

begin  
  declare @y int  
  set @y=2014  

  select datepart(dayofyear,dateadd(day,-1,'1/1/'+convert(char(4),@y+1)))  
end

I'm getting day 1 of the next year, subtracting one day to get the last day of the current year, then getting the day-of-year from that.

查看更多
登录 后发表回答