Home >Database >Mysql Tutorial >How Can I Dynamically Build SQL Queries with Parameterized Values When Column Names Are Variable?
Dynamic Query Building due to PARAMETER RESTRICTIONS
While executing queries involving dynamic column names, developers may encounter the limitation that column names cannot be parameterized. To circumvent this issue, one must dynamically build the query at runtime.
Consider the following non-working example:
SqlCommand command = new SqlCommand("SELECT @slot FROM Users WHERE name=@name; "); prikaz.Parameters.AddWithValue("name", name); prikaz.Parameters.AddWithValue("slot", slot);
As an alternative, white-list the "slot" input to prevent injection attacks and build the query as follows:
// TODO: verify that "slot" is an approved/expected value SqlCommand command = new SqlCommand("SELECT [" + slot + "] FROM Users WHERE name=@name; ") prikaz.Parameters.AddWithValue("name", name);
This approach ensures that "@name" remains parameterized, while dynamically handling the variable column name.
The above is the detailed content of How Can I Dynamically Build SQL Queries with Parameterized Values When Column Names Are Variable?. For more information, please follow other related articles on the PHP Chinese website!