title: How to call columns dynamically in SQL Server?
body: <p>Please find below the script. I am trying to call the column names dynamically. The first 3 columns are <code>LOC</code>, <code>Product</code> and <code>status</code> are fixed. There are 53 columns atfer that from 2015 and for 2016 like: <code>1-2015</code>, <code>2-2015</code>, <code>3-2015</code> ... <code>53-2015</code> and <code>1-2016</code>, <code>2-2016</code>, <code>3-2016</code> ... <code>53-2016</code>. I want to build dynamic SQL to call all that columns. I am doing this because I want it in specific order which i'm not able to get if i use SELECT * FORM TABLE.</p>
  
  <pre><code>declare @values varchar(max)
  
  declare @n varchar(10) 
  
  set @n = 1
  
  set @values = '
     SELECT[LOC]
     ,[PRODUCT]
     ,[STATUS]
     ,['+@n+'-2015]
     ,['+@n+'-2016]
  FROM [LGI_Temp].[dbo].[Temp_PIVOT]';
  exec(@values);
  </code></pre>
  
  <p>This gives me result like:</p>
  
  <pre><code>LOC     PRODUCT     STATUS  1-2015    1-2016
  </code></pre>
  
  <p>I want it for all the 53 values in each year.</p>
  
  <p>How to do that?</p>