如何在 SQL 中列出两个日期参数之间的所有日期

How can I list all dates between two date parameters in SQL(如何在 SQL 中列出两个日期参数之间的所有日期)
本文介绍了如何在 SQL 中列出两个日期参数之间的所有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何在不创建存储过程、日历表或递归函数的情况下,在 SQL Server 中列出两个日期参数之间的所有日期?

How can I list all dates between two date parameters in SQL Server, without creating a stored procedure, calendar table or recursive function?

推荐答案

这使用 Master 数据库中 spt_values 表上的 Row_Number 来创建日期范围内的年、月和日期列表.然后将其内置到日期时间字段中,并进行过滤以仅返回输入的日期参数内的日期.

This uses Row_Number on the spt_values table in Master database to create a list of years, months and dates within the date range. This is then built into a datetime field, and filtered to only return dates within the date parameters entered.

执行速度非常快,并在不到 1 秒的时间内返回 500 年的日期(182987 天).

Very quick to execute and returns 500 years worth of dates (182987 days) in less than 1 second.

Declare @DateFrom datetime = '2000-01-01'
declare @DateTo datetime = '2500-12-31'
Select
*
From
    (Select
    CAST(CAST(years.Year AS varchar) + '-' + CAST(Months.Month AS varchar) + '-' + CAST(Days.Day AS varchar) AS DATETIME) as Date

    From
    (select row_number() over(order by number) as Year from master.dbo.spt_values) as Years
    join (select row_number() over(order by number) as Month from master.dbo.spt_values) as Months on 1 = 1
    join (select row_number() over(order by number) as Day from master.dbo.spt_values) as Days on 1 = 1
    Where 
    Years.Year between datepart(year,@DateFrom) and datepart(year,@DateTo)
    and Months.Month between 1 and 12
    and 
    Days.Day between 1 and datepart(day,dateadd(day,-1,dateadd(month,1,(CAST(CAST(Years.Year AS varchar)+'-' + CAST(Months.Month AS varchar) + '-01' AS DATETIME)))))
    ) as Dates
Where Dates.Date between @DateFrom and @DateTo

order by 1

这篇关于如何在 SQL 中列出两个日期参数之间的所有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)