为什么Access在这里要求参数?

时间:2014-07-22 21:58:16

标签: sql ms-access-2007 query-parameters

为了测试针对MS Access“数据库”的特定查询是否应该返回任何记录(它不是),我在Access中运行它,如下所示:

SELECT TOP 5 t_accounts.account_no as AccountID, IIF(ISNULL(t_accounts.name),'[blank]',t_accounts.name) AS Name 
FROM t_accounts 
INNER JOIN td_department_accounts ON (t_accounts.account_no = td_department_accounts.account_no) 
WHERE (AccountID >= 1) AND type = 'DE'

Top 5 ”和“ AccountID> = 1 ”是我在代码中使用的硬编码版本:

cmd.CommandText = 
        string.Format(
        @"SELECT TOP {0} t_accounts.account_no as AccountID, IIF(ISNULL(t_accounts.name),'[blank]',t_accounts.name) AS Name 
        FROM t_accounts 
        INNER JOIN td_department_accounts ON (t_accounts.account_no = td_department_accounts.account_no) 
        WHERE (AccountID >= @firstId) AND type = 'DE'", CountToFetch);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@firstId", FirstId);

然而Access提示我:

enter image description here

(如果我输入“1”,它会返回一些记录)。

我必须做些什么才能让Access的查询运行过程理顺并且正确?还是我有眩晕?

更新

或许有一个线索是,使用上面显示的C#代码,我得到了,“没有给出一个或多个必需参数的值。”为什么?唯一的参数是firstId,它的值确实提供了......?!?

更新2

尽管它有效,但在它上运行代码分析会导致这个庄严的工具皱起眉头,皱眉和咆哮:

CA2100  Review SQL queries for security vulnerabilities The query
string passed to 'OleDbCommand.CommandText.set(string)' in
'NRBQSQLRepository.GetNDepartmentsFromID(string, int)' could contain
the following variables 'CountToFetch'. If any of these variables
could come from user input, consider using a stored procedure or a
parameterized SQL query instead of building the query with string
concatenations. 

1 个答案:

答案 0 :(得分:3)

来自Why does Access want me to enter a parameter value?

  

Access打开时显示“输入参数值”对话框   包含Access无法识别的标识符或表达式的对象   解释

在这种情况下,AccountIDt_accounts.account_no的字段别名。您试图在Where子句中引用字段别名。你不能这样做。

更改

WHERE (AccountID >= 1) AND type = 'DE'

WHERE (t_accounts.account_no>= 1) AND type = 'DE'