question

tombiernacki avatar image
tombiernacki asked

Get year date while loop

I am trying to create a while loop counter to get year based on the @year and @id so for example if I chose year 2012 I will get 2012 and 2013 if @id =1 if @id =2 then I will get 2012,2013,2014. I did the Select year(getdate()) to get the current year but am stuck on creating the loop to insert the years into table variable based on the @year and @id. Any help would be appreciated.
dateswhile-loop
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

tombiernacki avatar image tombiernacki commented ·
I came up with the following.... This works well based on todays year declare @id int declare @year int DECLARE @GETYEAR TABLE ( YEAR INT ) SET @id = 0 SET @year = (SELECT YEAR(GETDATE())) WHILE @year <= (SELECT YEAR(GETDATE())+ @id) BEGIN SET @year = @year + 1 INSERT INTO @GETYEAR VALUES(@year) END INSERT INTO @GETYEAR(YEAR) SELECT YEAR(GETDATE()) SELECT * FROM @GETYEAR ORDER BY YEAR
0 Likes 0 ·
tombiernacki avatar image
tombiernacki answered
declare @id int declare @year int DECLARE @GETYEAR TABLE ( YEAR INT ) SET @year = 2010 declare @CurrentYear int SET @id = 0 SET @CurrentYear = (SELECT YEAR(GETDATE())) INSERT INTO @GETYEAR VALUES(@year) WHILE @year <= (SELECT YEAR(GETDATE())+ @id) BEGIN SET @year = @year + 1 INSERT INTO @GETYEAR VALUES(@year) END SELECT * FROM @GETYEAR ORDER BY YEAR
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Usman Butt avatar image
Usman Butt answered
@tombiernacki I would not recommend a Loop to acheive this. SQL Server is not build for such programming. Also, for your own good please always try to build a solution using a set based approach. Your problem can be easily done with a Recursive cte OR using cteTally numbers table (Arbitrary numbers table). Using cteTally numbers table this is how it can be done Declare @year INT, @id INT SELECT @year = 2012, @id = 2 ;WITH CTETally AS ( SELECT TOP(@id+1) N = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d (n), (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n), (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n) ) SELECT @year + N - 1 FROM CTETally ORDER BY N Hope it helps.
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.