Creating @X rows with future years

22 Views Asked by At

I am trying to create a SQL which would display @X rows with future years:

year(now())+1
year(now())+2
year(now())+3
...

@X is a user-defined variable.

I came only to using union select but it looks nasty and works for reasonably low @x:

set @x:=3;
select year(now())+1 as year
union select if(@x>1, year(now())+2,null) as year
union select if(@x>2, year(now())+3,null) as year
union select if(@x>3, year(now())+4,null) as year;
1

There are 1 best solutions below

0
sticky bit On

That'd be the domain of recursive CTEs available since MySQL 8.

SET @x = 5;

WITH RECURSIVE
years
AS
(
SELECT year(now()) year
UNION ALL
SELECT year + 1
       FROM years
       WHERE year + 1 - year(now()) <= @x
)
SELECT *
       FROM years;

db<>fiddle