我对这个问题有不同的解释:“如何生成一定范围内的所有日期?”
这是一个解决方案:
--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