鉴于conn
是OdbcConnection
个对象且count
是int
,我如何将count作为参数用于查询?
...
var query = conn.CreateCommand();
query.CommandText = "select top ? * from players order by Points desc";
query.Parameters.Add("top", OdbcType.Int).Value = count;
var reader = query.ExecuteReader();
while (reader.Read())
{
...
}
...
这样我收到语法错误ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '@P1'.
如果不可能的话,我会尝试以正确的方式做到这一点吗?
答案 0 :(得分:2)
你可以这样做:
query.CommandText = "select top (@topparameter) * from players order by Points desc";
query.Parameters.AddWithValue("@topparameter", count.ToString());
如果您使用SqlServer
,请使用SqlConnection
和SqlCommand
,如:
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
using (SqlCommand query = new SqlCommand("select top (@topparameter) * from players order by Points desc", conn))
{
query.Parameters.AddWithValue("@topparameter", count.ToString());
var reader = query.ExecuteReader();
while (reader.Read())
{
}
}
}
答案 1 :(得分:2)
您还可以使用SET ROWCOUNT,其优点是可以使用整数作为参数并避免动态查询。
SET ROWCOUNT @top;
select * from table;
SET ROWCOUNT 0;