I am trying to use a stored procedure, which contains parameters, which should be used as column names. So for example something like this
Select * from table1 where @columnparameter = 'test'
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
Previously (before I was using the dynamic sql statement) I used this lines
[...]
AND (table1.userId = ISNULL(@userId, table1.userId))
AND (table1.fileId = ISNULL(@fileId, table1.fileId))
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
Right now, the statements are like this:
'AND (q.userId = ISNULL('+@l_userId+', q.userId))
AND (q.fileId = ISNULL('+@l_docId+', q.fileId))'
And in this case I don't get any results at all. It seems, that the sql command isn't executed at all.
But I also tried:
'AND (q.userId = '+ISNULL(@l_userId, 'q.userId')+')
AND (q.userId ='+ISNULL(@l_docId, 'q.fileId')+')'
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...
I also tried some different approaches, but all were misleading and caused various exceptions etc.
For me it's quite confusing working with dynamic sql because of the armada of quotation marks :D
@l_userIdand@l_docId? If some numeric - cast them into nvarchar.ISNULLon a parameter?