Sean P
Sean P

Reputation: 949

Parameterized query with parameter in select returns invalid data

I have the following code:

string connectionString = 
    "Provider=Microsoft.JET.OLEDB.4.0;" + 
    "data source=" + processProgramPath + ";";

using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    connection.Open();
    using (OleDbCommand command = new OleDbCommand(
        "SELECT @Value " +
        "FROM BONDPARAMETERS " +
        "WHERE BONDPARAMETERS.SetName = @SetName", connection))
    {
        command.Parameters.AddWithValue("@Value", value);
        command.Parameters.AddWithValue("@SetName", setName);               

        var result = command.ExecuteScalar();
        return result.ToString();
    }
}

What I am expecting to get is 760 as a result. However I am getting the title for the column which is StartForce.

value = "StartForce" setName = "450(18)-F-OE"

If I change the using to this:

using (OleDbCommand command = new OleDbCommand("SELECT "+value+" " +

it works. What gives?

Thanks in advance

Upvotes: 0

Views: 824

Answers (1)

TheNextman
TheNextman

Reputation: 12566

You can't build SQL dynamically with parameters like that. See this question: Using C# SQL Parameterization on Column Names

Upvotes: 1

Related Questions