Home >Database >Mysql Tutorial >How Can I Dynamically Build SQL Queries with Parameterized Values When Column Names Are Variable?

How Can I Dynamically Build SQL Queries with Parameterized Values When Column Names Are Variable?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 04:38:15707browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn