Parameters in SqlCommand: Alternative for Column Name Parameterization
In C#, stored procedures are not always the desired solution for dynamic column name parameterization. The question arises: can we accomplish this without resorting to stored procedures?
The short answer is no. SqlCommand does not support parameterization for column names. However, we can construct the query dynamically at runtime.
To prevent injection attacks, it's crucial to validate that the input column name ("slot" in this case) is approved and expected. With this in mind, we can 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 method allows us to parameterize input values like "@name" while dynamically constructing the query based on the specified column name.
The above is the detailed content of Can C# SqlCommand Parameterize Column Names Without Stored Procedures?. For more information, please follow other related articles on the PHP Chinese website!