我有一个Dimension表,我需要在接下来的50年里显示YYYYMM。我确信有一种方法可以在不手动输入数据的情况下执行此操作,但我不确定这样做的适当方法。
我的桌子有
An ID which is an int that will display YYYYMM
the month that will be a varchar(2) to display MM
and the year that will be a varchar(4) to display YYYY
有人能帮我解决这个问题吗?我之前从未真正编写过脚本,我在网上看到的示例更多地显示了日期时间数据类型。
我可能也想在几年前就已经存在的数据开始。我们说2010 - 2070
答案 0 :(得分:1)
这对我有用
DECLARE @t TABLE
(
id INT ,
m VARCHAR(2) ,
y VARCHAR(4)
)
DECLARE @i INT = 1
DECLARE @today DATE = '20150121'
DECLARE @endDate DATE = DATEADD(YEAR, 50, @today)
WHILE @today <= @endDate
BEGIN
INSERT INTO @t
( id ,
m ,
y
)
VALUES ( CAST(LEFT(CONVERT(CHAR(8), @today, 112), 6) AS INT) ,
SUBSTRING(CONVERT(CHAR(8), @today, 112), 5, 2) ,
LEFT(CONVERT(CHAR(8), @today, 112), 4)
)
SET @today = DATEADD(MONTH, 1, @today)
END
输出:
id m y
201501 01 2015
201502 02 2015
201503 03 2015
201504 04 2015
201505 05 2015
201506 06 2015
201507 07 2015
201508 08 2015
201509 09 2015
201510 10 2015
201511 11 2015
201512 12 2015
201601 01 2016
201602 02 2016
201603 03 2016
. . .
206410 10 2064
206411 11 2064
206412 12 2064
206501 01 2065
答案 1 :(得分:0)
我将使用与stacked cte
的计数表执行此操作。试试这个
declare @start_year varchar(4)='2010',@end_year varchar(4)='2070'
;WITH e1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e2 CROSS JOIN e2 AS b), -- 100*100
e4(n) AS (SELECT 1 FROM e3 CROSS JOIN (SELECT TOP 5 n FROM e1) AS b) -- 5*10000
,e5 as (SELECT Dateadd(Month, Row_number()OVER (
ORDER BY n) - 1, Cast(@start_year + '-01-01' AS DATE)) AS dates
FROM e4)
SELECT Id=LEFT(CONVERT(CHAR(8), dates, 112), 6),
[Month]=Month(dates),
[Year]=Year(dates)
FROM e5
WHERE Year(dates) <= @end_year