title: Dynamic SQL to use columns as parameter. ISNULL() function isn't working anymore
body: <p>I am trying to use a stored procedure, which contains parameters, which should be used as column names. So for example something like this</p>
  
  <pre><code>Select * from table1 where @columnparameter = 'test'
  </code></pre>
  
  <p>One approach I've found to realize it, was to use a dynamic sql and so far it is working. But I also want to use the ISNULL function, to check if another parameter is null and if it is, it should return all values of the specified column</p>
  
  <p>Previously (before I was using the dynamic sql statement) I used this lines</p>
  
  <pre><code>[...]
  AND (table1.userId = ISNULL(@userId, table1.userId))
  AND (table1.fileId = ISNULL(@fileId, table1.fileId))
  </code></pre>
  
  <p>and this worked fine for me, but since I am using the dynamic sql, I am not getting any results anymore, when I am executing the stored procedure.
  I have found out, that I get at least results, when I am removing the "ISNULL"-Lines</p>
  
  <p>Right now, the statements are like this:</p>
  
  <pre><code>'AND (q.userId = ISNULL('+@l_userId+', q.userId))
  AND (q.fileId = ISNULL('+@l_docId+', q.fileId))'
  </code></pre>
  
  <p>And in this case I don't get any results at all. It seems, that the sql command isn't executed at all.</p>
  
  <p>But I also tried:</p>
  
  <pre><code>'AND (q.userId = '+ISNULL(@l_userId, 'q.userId')+')
  AND (q.userId ='+ISNULL(@l_docId, 'q.fileId')+')'
  </code></pre>
  
  <p>In this case, I get at least results, when the parameters are null, but as soon as they have a value, I get the error message, that the value of the parameter is an invalid column name...</p>
  
  <p>I also tried some different approaches, but all were misleading and caused various exceptions etc.</p>
  
  <p>For me it's quite confusing working with dynamic sql because of the armada of quotation marks :D</p>