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
Release: 2024-12-18 04:38:15
Original
704 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template