如何将限制定义为参数?

时间:2014-03-07 16:13:21

标签: c# tsql odbc

鉴于connOdbcConnection个对象且countint,我如何将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'.

如果不可能的话,我会尝试以正确的方式做到这一点吗?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

query.CommandText = "select top (@topparameter) * from players order by Points desc";
query.Parameters.AddWithValue("@topparameter", count.ToString());

如果您使用SqlServer,请使用SqlConnectionSqlCommand,如:

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;

阅读documentation