Sql 将参数添加到命令ADO.NET

Sql 将参数添加到命令ADO.NET,sql,ado.net,Sql,Ado.net,我试图使用以下代码从数据库中选择数据: getForecastsCommand.CommandText = @"SELECT TOP @Count * FROM Forecasts Order by [ForecastId] DESC"; var countParam = getForecastsCommand.CreateParameter(); countParam.ParameterName = "@Count"; countParam.Value = count;

我试图使用以下代码从数据库中选择数据:

 getForecastsCommand.CommandText = @"SELECT TOP @Count * FROM Forecasts Order by [ForecastId] DESC";

   var countParam = getForecastsCommand.CreateParameter();
   countParam.ParameterName = "@Count";
   countParam.Value = count;
   countParam.DbType = DbType.Int32;
   getForecastsCommand.Parameters.Add(countParam);
但这是行不通的:

Incorrect syntax near '@Count'.

为什么不工作?

该语法看起来像Microsoft Access数据库。如果是,则不支持TOP的参数。您必须构建字符串

@"SELECT TOP " + Count + " * FROM Forecasts Order by [ForecastId] DESC";

请通过[ForecastId]DESC从预测订单中选择TOP(@Count)*来尝试此


请注意,@count用括号括起来。

您应该在正在使用的数据库中添加注释。另外,请在此处查找有关TOP子句的其他信息