title: SQL Server : generate select statement dynamically inside a stored procedure with dynamic column names
body: <p>I want to generate a select statement inside a SQL Server stored procedure. I have the column names in SQL parameters.</p>
  
  <p>I am trying to generate the select statement programatically with chosen column names, but can't seem to find correct syntax inside stored procedure.</p>
  
  <pre><code>CREATE PROCEDURE dbo.aProc
       @testCondition int,
       @colCount int,
       @column_1 varchar(100) = null,
       ....
      @column_40 varchar(100) null
  AS
    DECLARE @qry nvarchar(3000)
    DECLARE @Iterator int
  
    SET @testtype = 2
    SET @Iterator = 0
    SET @qry  ='SELECT '
  
    WHILE (@Iterator &lt; @colCount-1)
      BEGIN
          SET @qry = @qry + ''+@column_''+CAST(@Iterator as varchar(2))+',''
          Set @Iterator = @Iterator + 1
      END
  
  
    SET @qry = @qry + ''@column_+CAST(@colCount as varchar(2)) FROM aTable where aCol = @testCondition 
  </code></pre>