我正在尝试创建20年(从2000年到2020年)的日历表。目标是每天有一行,以及一些其他列,这些列将根据生成的日历日期使用逻辑。例如,将“一”列作为日历日期(2000-01-01),将“年”列从日历日期列中的值中读取年份(2000)。
该表的代码如下:
CREATE TABLE TEST.CALENDAR(
CALENDAR_DATE DATE NOT NULL,
CALENDAR_YEAR INTEGER NOT NULL,
CALENDAR_MONTH_NUMBER INTEGER NOT NULL,
CALENDAR_MONTH_NAME VARCHAR(100),
CALENDAR_DAY_OF_MONTH INTEGER NOT NULL,
CALENDAR_DAY_OF_WEEK INTEGER NOT NULL,
CALENDAR_DAY_NAME VARCHAR(100),
CALENDAR_YEAR_MONTH INTEGER NOT NULL);
目前,我有一堆插入语句,这些语句会在20年内为该表手动插入行。我正在寻找使用变量代替插入语句,并且该插入语句将以每日增量插入数据,直到开始日期变量不小于结束日期变量为止。
目前,我无法使它完全起作用,更不用说为任何其他列提供任何逻辑了。
变量insert语句的代码:
declare startdate DATE, enddate DATEset startdate = '2000-01-01'
set enddate = DATEADD(yy,20,startdate)
while startdate < enddate
begin insert into TEST.CALENDAR (CALENDAR_DATE) select startdate
set startdate = DATEADD(dd,1,startdate) end
有人会对我如何使它起作用有任何想法吗?
您可以使用DB2递归查询和日期函数来做到这一点:
考虑:
with cte (
calendar_date,
calendar_year,
calendar_month_number,
calendar_month_name,
calendar_day_of_month,
calendar_day_of_week,
calendar_day_name
) as (
select
calendar_date,
year(calendar_date),
month(calendar_date),
monthname(calendar_date),
dayofmonth(calendar_date),
dayofweek(calendar_date),
dayname(calendar_date)
from (values(date('2000-01-01'))) as t(calendar_date)
union all
select
calendar_date + 1,
year(calendar_date + 1),
month(calendar_date + 1),
monthname(calendar_date + 1),
dayofmonth(calendar_date + 1),
dayofweek(calendar_date + 1),
dayname(calendar_date + 1)
from cte where calendar_date < date('2021-01-01')
)
select * from cte
注意:我不清楚该列的CALENDAR_YEAR_MONTH
含义,因此我将其分开。
前10天的DB Fiddle演示:
CALENDAR_DATE | CALENDAR_YEAR | CALENDAR_MONTH_NUMBER | CALENDAR_MONTH_NAME | CALENDAR_DAY_OF_MONTH | CALENDAR_DAY_OF_WEEK | CALENDAR_DAY_NAME ------------:| ------------:| --------------------:| ------------------:| --------------------:| -------------------:| ----------------:2000年1月1日 | 2000 | 1 | 一月 1 | 7 | 2000年1月2日星期六 | 2000 | 1 | 一月 2 | 1 | 周日 | 2000 | 1 | 一月 3 | 2 | 星期一 2000-01-04 | 2000 | 1 | 一月 4 | 3 | 2000年1月5日星期二 | 2000 | 1 | 一月 8 | 7 | 星期六 2000-01-05 | 2000 | 1 | 一月 5 | 4 | 2000年1月6日星期三 | 2000 | 1 | 一月 6 | 5 | 2000年1月7日星期四 | 2000 | 1 | 一月 7 | 6 | 2000年1月9日,星期五 2000-01-09 | 2000 | 1 | 一月 9 | 1 | 2000年1月10日星期日 | 2000 | 1 | 一月 10 | 2 | 星期一
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句