日期:2014-05-19  浏览次数:20479 次

如何用一个SQL语句,把某月所有的天数列出来。
如:列出2006.7所有的日期:      
    2006.7.1      
    2006.7.2      
    2006.7.3      
    ……      
    2006.7.31      
    要求,使用SQL语句,最好是一句语句


如何用一个SQL语句,把某月所有的天数列出来。


各位,有什么好方法吗?

------解决方案--------------------
一句語句比較困難,借用下臨時表

Declare @Year int, @Month Int
Select @Year = 2007, @Month = 7
Select TOP 50 ID = Identity(Int, 0, 1) Into #T From SysColumns
Select Convert(Varchar(10), DateAdd(dd, ID, Cast(Rtrim(@Year) + '- ' + Rtrim(@Month) + '- ' + '01 ' As DateTime)), 120) From #T
Where ID < DateDiff(dd, Cast(Rtrim(@Year) + '- ' + Rtrim(@Month) + '- ' + '01 ' As DateTime), DateAdd(mm, 1, Cast(Rtrim(@Year) + '- ' + Rtrim(@Month) + '- ' + '01 ' As DateTime)))
Drop Table #T
--Result
/*
2007-07-01
2007-07-02
2007-07-03
2007-07-04
2007-07-05
2007-07-06
2007-07-07
2007-07-08
2007-07-09
2007-07-10
2007-07-11
2007-07-12
2007-07-13
2007-07-14
2007-07-15
2007-07-16
2007-07-17
2007-07-18
2007-07-19
2007-07-20
2007-07-21
2007-07-22
2007-07-23
2007-07-24
2007-07-25
2007-07-26
2007-07-27
2007-07-28
2007-07-29
2007-07-30
2007-07-31
*/
------解决方案--------------------
if object_id( 'tempdb..#tmp ') is not null
drop table #tmp
GO
----创建循环临时表
select top 31 id = identity(int,0,1) into #tmp from syscolumns,sysobjects
----创建测试数据
declare @t table(d varchar(10))
insert @t
select '2006.7 ' union all
select '2006.9 '
----查询
select dateadd(day,b.id,a.d + '.01 ') from @t as a
inner join #tmp as b on dateadd(day,b.id,a.d + '.01 ') <= dateadd(day,-1,dateadd(month,1,a.d + '.01 '))
----清除测试环境
drop table #tmp

/*结果
------------------------------------------------------
2006-07-01 00:00:00.000
......
2006-07-31 00:00:00.000

2006-09-01 00:00:00.000
......
2006-09-30 00:00:00.000
*/
------解决方案--------------------
建一个辅助表

create table #tab
(
id int
)
insert into #tab select 0
insert into #tab select 1
insert into #tab select 2
insert into #tab select 3
insert into #tab select 4
insert into #tab select 5
insert into #tab select 6
insert into #tab select 7
insert into #tab select 8
insert into #tab select 9
insert into #tab select 10
insert into #tab select 11
insert into #tab select 12
insert into #tab select 13
insert into #tab select 14
insert into #tab select 15
insert into #tab select 16
insert into #tab select 17
insert into #tab select 18
insert into #tab select 19
insert into #tab select 20
insert into #tab select 21
insert into #tab select 22
insert into #tab select 23
insert into #tab select 24
insert into #tab select 25
insert into #tab select 26
insert into #tab select 27
insert into #tab select 28
insert into #tab select 29
insert into #tab select 30
insert into #tab select 31

--语句
declare @mydate varchar(6)
set @mydate = '200606 '