title: Use the result of one query to create a new select statement using SQL only
body: <p>I have the impression that the following is not possible using SQL but wanted to ask here before dismissing it entirely. </p>
  
  <p>In a very poorly designed DB I have to use, one table holds as values the field names of another table. Simplified, the table, let's call it ColumnTable, looks like this: </p>
  
  <pre><code>ID          ColumnName
  ------      -----------
  23          Column_1
  24          Column_2
  </code></pre>
  
  <p>The other table, let's call it ContentTable, accordingly, looks as follows:</p>
  
  <pre><code>ID          Column_1          Column_2
  ------      -----------       ----------
  101         Somecontent1       Somecontent3
  102         Somecontent2       Somecontent4
  </code></pre>
  
  <p>As you can see, there are no foreign keys I can use, the whole DB is an absolute nightmare. Redesigning the DB to bring it in a normal form is out of the questions since a closed source application depends on the DB having exactly this layout. The layout being more one of a registry than of a relational DB. </p>
  
  <p>Anyway, as you have already guessed, to query the content from the ContentTable, one first needs to get the respective field name. I am quite certain that the application does this in two steps: It first queries the name of the field, then it uses the result of this query to create a new query string to query the content. </p>
  
  <p>To make an example, we know that we wish to query the row with the ID 101 in the ContentTable but we don't know which column. But we know that we can find the name of the column in the row with the ID 23 of the ColumnTable. I assume the application does this as follows.</p>
  
  <pre><code>int fieldsID = 23
  int contentID = 101
  string columnName
  string neededResult
  
  columnName = SQLQuery("SELECT ColumnName FROM ColumnTable WHERE ID =" + fieldsID)
  echo columnName //Will return Column_1
  
  neededResult = SQLQuery("SELECT " + columnName + "FROM ContentTable")
  echo neededResult //Will return Somecontent1
  </code></pre>
  
  <p>Is there any way to do this using only SQL? </p>
  
  <p><code>SELECT (SELECT ColumnName FROM ColumnTable WHERE ID = 1) FROM ContentTable</code> (to receive the desired select statement <code>SELECT Column_1 FROM ContentTable WHERE ID = 1</code>) obviously won't work, since the nested SELECT statement just creates a new field with the query result for content. </p>
  
  <p>As mentioned, doing this from code is no problem but it's inefficient. Is there a way to do this in SQL? While this question is relevant for SQL in general, this specific DB is in MSSQL so if there is some trick to do this efficiently in T-SQL, for example using a function or SPROC, I'll appreciate the advice. </p>