生成日期序列

首先创建Tally Table。

set nocount on;

if object_id('dbo.Tally') is not null drop table dbo.tally

go

select top 10000 identity(int,1,1) as ID

into dbo.Tally from master.dbo.SysColumns

alter table dbo.Tally

add constraint PK_ID primary key clustered(ID)

go

select * from dbo.Tally

假设我们要生成从当前日期到接下来 25 天的日期列表。 无需使用 while 循环来创建日期列表。 我们可以使用 Tally 表轻松生成日期列表。

-- 生成日期范围

declare @StartDate  datetime

declare @EndDate datetime

set @StartDate=getdate()

set @EndDate=getdate()+25

select  dateadd(DD,ID-1,@StartDate) as [DATE],

day(dateadd(DD,ID-1,@StartDate)) as [DAY],

month(dateadd(DD,ID-1,@StartDate)) as [MONTH],

year(dateadd(DD,ID-1,@StartDate)) as [YEAR]

from dbo.Tally

where dateadd(DD,ID-1,@StartDate)<=@EndDate

Tally Tables

Tally 表就像其他的表一样,只有一列,根据您的要求保存从 1(或者 0)到任何大数的唯一数字。 在 Tally 表中,应根据您的系统或者应用程序取大数。 所以尽量避免使用非常高的数字。

在 SQL Server 中使用 Tally 表生成日期序列

在本文中,将介绍如何使用 Tally Tables 创建日期范围。 Tally Table 是一个单列表,用于以循环方式计算任何内容。 它通过减少执行时间来提高查询的性能。

日期:2020-06-02 22:17:48 来源:oir作者:oir