我有這個問題的不同解釋:「如何生成所有在一定範圍內的日期」
下面是一個解決方案:
--define start and end limits
Declare @todate datetime, @fromdate datetime
Select @fromdate='2009-03-01', @todate='2009-04-10'
;With DateSequence(Date) as
(
Select @fromdate as Date
union all
Select dateadd(day, 1, Date)
from DateSequence
where Date < @todate
)
--select result
Select * from DateSequence option (MaxRecursion 1000)
有一個很好的article,顯示瞭如何生成使用CTE序列(數字,日期,時間)。
編輯:
澄清後,這個問題似乎是日期格式是輸入:DD/MM/YYYY。
SQL Server預計格式爲mm/dd/yyyy。
我只想運行SELECT語句前改造它:
-- Assuming two variables, @inputFromDate and @inputToDate, in the format of dd/mm/yyyy...
declare @fromDate varchar(10), @toDate varchar(10)
set @fromDate =
substring(@inputFromDate, 3, 2) + '/' +
substring(@inputFromDate, 1, 2) + '/' +
substring(@inputFromDate, 7, 4)
set @toDate =
substring(@inputToDate, 3, 2) + '/' +
substring(@inputToDate, 1, 2) + '/' +
substring(@inputToDate, 7, 4)
select * from SomeTable where dateCol >= @fromDate and dateCol < @toDate
-- you can change the <or>= comparisons according to your needs
你應該從問題的一個例子澄清你的問題。 – 2010-03-14 16:08:09