title: How to convert string to column name?
body: <p>I have two solutions to select some data from a table.</p>
  
  <p><strong>SOLUTION 1</strong></p>
  
  <pre><code>SELECT [ID]
        ,[SPAU10_EA]
        ,[SPAU10_EQ]
        ,[SPAU10_ore1]
        ,[SPAU10_nivel]
        ,[DateTime]
    FROM [dbo].[TblSPAU10]
  </code></pre>
  
  <p><strong>SOLUTION 2</strong></p>
  
  <p>I have a stored procedure with parameters which returns the same result as the above query. SP's query is like:</p>
  
  <pre><code> ALTER PROCEDURE [dbo].[PS_SpauOPompa]
  
  @DataStart datetime,
  @DataStop datetime,
  @val int
  AS
  BEGIN
  SET NOCOUNT ON;
  
  declare @sql NVARCHAR(max)
  declare @col1 varchar (25) 
  declare @col2 varchar(25)
  declare @col3 varchar (25)  
  declare @col4 varchar (25)  
  declare @col5 varchar (25)  
  declare @col6 varchar (25)  
  
  set @col1='ID'
  set @col2='SPAU'+CONVERT(VARCHAR, @val)+'_EA' 
  set @col3='SPAU'+CONVERT(VARCHAR, @val)+'_EQ'
  set @col4='SPAU'+CONVERT(VARCHAR, @val)+'_ore1'
  set @col5='SPAU'+CONVERT(VARCHAR, @val)+'_nivel'
  set @col6='DateTime'
  
  set @sql= 'select [ID], ' + @col2 + ',' + @col3 + ',' + @col4 + ',' + @col5 + ',' + @col6 + ' FROM [DBRap].[dbo].[TblSPAU'+CONVERT(VARCHAR, @val)+ '] WHERE DateTime between '''+CONVERT(VARCHAR(25), @DataStart,121)+ ''' and '''+CONVERT(VARCHAR(25), @DataStop,121)+''';'
  
  print @sql;
  
  
  EXEC sp_executesql  
      @sql, 
      N'@DataStart datetime, @DataStop datetime, @val int',  
      @DataStart, @DataStop, @val;
  END
  --execute [PS_SpauOPompa] '2018-12-13 15:58:46.940', '2018-12-21 10:51:10.713', 10
  </code></pre>
  
  <p>I'd like to combine the two solutions, meaning that instead of @sql string to put the select query from first solution. The problem I'm facing now is: how to convert from <code>varchar</code> variables to <code>[column_name]</code>?</p>
  
  <p>I tried, unsuccessfully,  in sp something like this:</p>
  
  <pre><code>SELECT @col1
        ,@col2
        ,@col3
        ,@col4
        ,@col5
        ,@col6
    FROM [dbo].[TblSPAU10]
  </code></pre>