Here I am going to explain the solution of a business problem which I gave to one of my friends.

There is a SQL Server table like below:

table

Data in my table:

data

Now the problem is that he wants to fetch record columns for after the current month: This means if the current month is February then the result set columns should show the month record for after February (March- December) or if the current month is March then the result set should show (April- December).

So for this I wrote the below stored procedure:

code

  1. CREATEPROCEDURE [dbo].[GETEMPLOYEE]
  2. AS
  3. DECLARE @CurrentMonth INT;
  4. SET @CurrentMonth=(SELECTMONTH(GETDATE())AS CurrentMonth)-- Get Current Month
  5. CREATETABLE #TempTable(ID VARCHAR(2), Name char(20))
  6. INSERTINTO #TempTable(ID, Name)VALUES ('1','JAN')
  7. INSERTINTO #TempTable(ID, Name)VALUES ('2','FEB')
  8. INSERTINTO #TempTable(ID, Name)VALUES ('3','MAR')
  9. INSERTINTO #TempTable(ID, Name)VALUES ('4','APR')
  10. INSERTINTO #TempTable(ID, Name)VALUES ('5','MAY')
  11. INSERTINTO #TempTable(ID, Name)VALUES ('6','JUN')
  12. INSERTINTO #TempTable(ID, Name)VALUES ('7','JUL')
  13. INSERTINTO #TempTable(ID, Name)VALUES ('8','AUG')
  14. INSERTINTO #TempTable(ID, Name)VALUES ('9','SEP')
  15. INSERTINTO #TempTable(ID, Name)VALUES ('10','OCT')
  16. INSERTINTO #TempTable(ID, Name)VALUES ('11','NOV')
  17. INSERTINTO #TempTable(ID, Name)VALUES ('12','DEC')
  18. DECLARE @listStr VARCHAR(MAX)
  19. SELECT @listStr =COALESCE(@listStr+',','')+ Name
  20. FROM #TempTable WHERE ID> @CurrentMonth
  21. DECLARE @sqlCommand varchar(1000)
  22. DECLARE @columnList varchar(75)
  23. SET @sqlCommand ='SELECT EMP_ID, EMP_NAME, '+ @listStr +' FROM EMPLOYEE '
  24. EXEC (@sqlCommand)
  25. DROPTABLE #TempTable
  26. GO
Now Execute This Stored Procedure:

Stored Procedure

Here you can see the result set is showing columns after the current month.