2012-07-20 75 views
0

我想使用此代碼來選擇DB數據:添加參數命令ADO.NET

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

爲什麼不是工作?

+1

您應該在您正在使用的數據庫上添加備註。 – Fionnuala 2012-07-20 11:29:50

回答

2

請試試這個SELECT TOP (@Count) * FROM Forecasts Order by [ForecastId] DESC

請注意,@count被括號包圍。

+0

另外,請在這裏http://sqlserver2000.databases.aspfaq.com/how-do-i-use-a-variable-in-a-top-clause-in-sql-server找到一些關於TOP子句的附加信息。 html – sergeyG 2012-07-20 11:58:30

+0

這是工作!非常感謝。 – 2012-07-20 12:05:03

0

該語法看起來像一個Microsoft Access數據庫。如果是,它不支持TOP的參數。你將不得不建立字符串。

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