我需要sql查询,它通过传递两个日期在所有日期之间给出结果。例如,假设我发送了01/01/2015
和10/01/2015
我需要传递日期之间的日期
结果应为:
01/01/2015
02/01/2015
03/01/2015
04/01/2015
05/01/2015
..
10/01/2015
我怎样才能做到这一点?
答案 0 :(得分:1)
您可以使用recursive CTE:
DECLARE @startDate DATETIME = '2015-01-01',
@endDate DATETIME = '2015-01-10'
;WITH dates AS(
SELECT @startDate AS date
UNION ALL
SELECT DATEADD(dd,1,date)
FROM dates
WHERE date<@endDate
)
SELECT * FROM dates
答案 1 :(得分:0)
使用Numbers table
生成日期。
DECLARE @StartDate DATETIME = convert(date,'01/01/2015',103) -- First Calendar date to include in table
DECLARE @EndDate DATETIME = convert(date,'10/01/2015',103) --Last calendar date to include in the table
;WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
E02(N) AS (SELECT 1 FROM E00 a, E00 b),
E04(N) AS (SELECT 1 FROM E02 a, E02 b),
E08(N) AS (SELECT 1 FROM E04 a, E04 b),
E16(N) AS (SELECT 1 FROM E08 a, E08 b),
E32(N) AS (SELECT 1 FROM E16 a, E16 b),
cteTally(N)
AS (SELECT Row_number()OVER ( ORDER BY N)
FROM E32),
CalendarBase
AS (SELECT CalendarDate = Dateadd(day, n - 1, @StartDate)
FROM cteTally
WHERE N <= Datediff(day, @StartDate, @EndDate + 1))
SELECT convert(varchar(30),CalendarDate ,103) as CalendarDate
FROM CalendarBase
从此link
引用答案 2 :(得分:0)
试试这个:
declare @strt date;
declare @end date;
select @strt = '20150101';
select @end = '20150110';
with dates as
(
select dt = dateadd(dd, 0, @strt)
where dateadd(dd, 1, @strt) <= @end
union all
select dateadd(dd, 1, dt)
from dates
where dateadd(dd, 1, dt) <= @end
)
select * from dates
答案 3 :(得分:0)
@Saurabh Dhakate
Use the below code:
declare @date1 date ='2015-01-10'
declare @date2 date ='2015-01-01'
declare @lv_table table (datepart1 date)
declare @count int
declare @count1 int = 1
set @count=(select day(@date1) )
print @count
while @count1<=@count
begin
insert into @lv_table
select dateadd(day,@count1,@date2)
set @count1=@count1+1
print @count1
end
select * from @lv_table