[英]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. 我承认,在C#中使用参数化查询时,我还是个新手(虽然学得很快!),所以我可能只是在这里忽略了一些东西,但是我似乎无法弄清楚该如何做。获取参数化查询对我有用。
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: 使用SQL Server Profiler,可以看到正在发出以下查询:
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: 如果直接在SQL Server Management Studio中运行该查询,则返回0。但是,如果我修改查询,如下所示:
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. 并运行它,我得到了51的计数,这是正确的。
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). 您只需要在SQL语句中取消对参数的引用(引用文本会使SQL Server将其视为文字)。 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周围的引号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.