本文介紹了如何在 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 中列出兩個日期參數之間的所有日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!