将参数添加到命令ADO.NET

时间:2012-07-20 11:27:15

标签: sql ado.net

我正在尝试使用此代码从db中选择数据:

 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'.

为什么不起作用?

2 个答案:

答案 0 :(得分:2)

请尝试SELECT TOP (@Count) * FROM Forecasts Order by [ForecastId] DESC

请注意@count被括号括起来。

答案 1 :(得分:0)

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

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