简体   繁体   中英

SqlCommand.Parameters.AddWithValue Not Returning Correct Results

I'll admit that I'm a bit of a newbie (though learning fast!) when it comes to using parameterized queries in C#, so I'm probably just overlooking something here, but I can't seem to figure out how to get a parameterized query to work for me.

Here is a much simplified example. If more information is needed, I am certainly willing to supply it.

using (SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "SELECT COUNT (*) FROM Sites WHERE ((STATE LIKE '@STATE'));
    command.Parameters.AddWithValue("@State", "MA");

    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        count = Convert.ToInt32(reader[0]);
    }
    reader.Close();
    connection.Close();
}

Using SQL Server Profiler, I can see that the following query is being issued:

exec sp_executesql N'SELECT COUNT (*) FROM Sites WHERE ((STATE LIKE ''@STATE''))',N'@STATE nvarchar(2)',@STATE=N'MA'

If I run that query directly in SQL Server Management Studio, it returns 0. If, however, I modify the query like this:

exec sp_executesql N'SELECT COUNT (*) FROM Sites WHERE ((STATE LIKE ''MA''))',N'@STATE nvarchar(2)',@STATE=N'MA'

And run it, I get a count of 51 back, which is correct.

What am I missing here?

You just need to unquote your parameter in the SQL statement (quoting text makes SQL Server treat it as a literal). Change this:

command.CommandText = "SELECT COUNT (*) FROM Sites WHERE ((STATE LIKE '@STATE'));

to this:

command.CommandText = "SELECT COUNT (*) FROM Sites WHERE ((STATE LIKE @STATE));

您不需要@STATE周围的引号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM