如何生成一个表,每行代表每个月的最后一天?

时间:2015-05-19 15:09:12

标签: sql sql-server-2008

我需要生成一个表格,其日期值如下所示:

01/31/2015
02/28/2015
03/31/2015
04/30/2015
....
12/31/2015

每个值代表每个月的最后一天。实现这一目标的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

@sDate是开始日期,@ eDate是结束日期。

declare @sDate datetime,
        @eDate datetime

select  @sDate = '2013-02-25',
        @eDate = '2013-04-25'

;with cte as (
  select convert(date,left(convert(varchar,@sdate,112),6) + '01') startDate,
         month(@sdate) n
  union all
  select dateadd(month,n,convert(date,convert(varchar,year(@sdate)) + '0101')) startDate,
        (n+1) n
  from cte
  where n < month(@sdate) + datediff(month,@sdate,@edate)
)
select dateadd(day,-1,dateadd(month,1,startdate)) as enddate
from cte

结果:

2013-02-28
2013-03-31
2013-04-30

答案 1 :(得分:1)

SELECT MonthEnd = DATEADD(ms, -3, DATEADD(m, DATEDIFF(m, 0, GETDATE()) + 1 + A.N, 0))
FROM (VALUES -- Feel free to replace this with some sort of numbers table
   (0), (1), (2), (3), (4), (5)
) A (N) 

答案 2 :(得分:0)

您可以使用EOMONTH来结束每个月,并根据您想要停止的时间循环。当然,您可以将它们选择到临时表或其他东西中供以后使用....

bash 'install_something' do
  user 'root'
  cwd '/tmp'
  code <<-EOH
  wget http://www.example.com/tarball.tar.gz
  tar -zxf tarball.tar.gz
  cd tarball
  ./configure
  make
  make install
  EOH
end