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:

Data in my table:

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:
- CREATEPROCEDURE [dbo].[GETEMPLOYEE]
- AS
- DECLARE @CurrentMonth INT;
- SET @CurrentMonth=(SELECTMONTH(GETDATE())AS CurrentMonth)-- Get Current Month
- CREATETABLE #TempTable(ID VARCHAR(2), Name char(20))
- INSERTINTO #TempTable(ID, Name)VALUES ('1','JAN')
- INSERTINTO #TempTable(ID, Name)VALUES ('2','FEB')
- INSERTINTO #TempTable(ID, Name)VALUES ('3','MAR')
- INSERTINTO #TempTable(ID, Name)VALUES ('4','APR')
- INSERTINTO #TempTable(ID, Name)VALUES ('5','MAY')
- INSERTINTO #TempTable(ID, Name)VALUES ('6','JUN')
- INSERTINTO #TempTable(ID, Name)VALUES ('7','JUL')
- INSERTINTO #TempTable(ID, Name)VALUES ('8','AUG')
- INSERTINTO #TempTable(ID, Name)VALUES ('9','SEP')
- INSERTINTO #TempTable(ID, Name)VALUES ('10','OCT')
- INSERTINTO #TempTable(ID, Name)VALUES ('11','NOV')
- INSERTINTO #TempTable(ID, Name)VALUES ('12','DEC')
- DECLARE @listStr VARCHAR(MAX)
- SELECT @listStr =COALESCE(@listStr+',','')+ Name
- FROM #TempTable WHERE ID> @CurrentMonth
- DECLARE @sqlCommand varchar(1000)
- DECLARE @columnList varchar(75)
- SET @sqlCommand ='SELECT EMP_ID, EMP_NAME, '+ @listStr +' FROM EMPLOYEE '
- EXEC (@sqlCommand)
- DROPTABLE #TempTable
- GO

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

SubashPosted Aug 22, 2016, 10:39 PM
Thanks
Pankaj Kumar ChoudharyPosted Apr 3, 2016, 8:34 AM
I request you to check this code and inform if this is not correct code according your query.......
Pankaj Kumar ChoudharyPosted Apr 3, 2016, 8:34 AM
ALTER PROCEDURE [dbo].[GETEMPLOYEE] AS BEGIN DECLARE @Col_Id int; SET @Col_Id =(SELECT MONTH(GETDATE())AS CurrentMonth) DECLARE @s VARCHAR(500) SELECT @s = ISNULL(@s+', ','') + c.name FROM sys.all_columns c join sys.tables t ON c.object_id = t.object_id WHERE t.name = 'Employee_New' AND c.column_id>@Col_Id DECLARE @Query varchar(MAX) SET @Query ='SELECT EMP_ID, EMP_NAME, '+ @s +' FROM Employee_New ' EXEC (@Query) END
Pankaj Kumar ChoudharyPosted Apr 3, 2016, 8:34 AM
Nice Post Sir.. Few Day ago i did same task and my solution was little different from your solution so think to write my code also because i think two is more better than one solution. My code is below