Search code examples
c#asp.netsqlsqldatasource

Dynamic Where Clause - Some variables not passing


I was wondering if the below scenario will work? I am having trouble with it.

I have a smart tag SQLDataSource with a query like such:

    SELECT [col1], [col2], [col3] FROM [Table1] WHERE (@SubType = @SubID) ORDER BY [col1] ASC

No matter where or how I set the @SubType parameter, it does not work, yet if I change the query to WHERE [col1] = @SubID (removing the @SubType) it works fine.

Can I set a parameter as a field name to compare against like my query does?


Solution

  • That's not how parameters work. Parameters are not string replacement. They work with values, not database objects names (Columns, Tables, etc.).

    The solution is to first assemble the SQL query with the desired columns (code behind) and then set the parameter's values.