简体   繁体   English

子查询中带有OleDbCommand的“条件表达式中的数据类型不匹配”

[英]“Data type mismatch in criteria expression” with an OleDbCommand in subquery

I am getting a "Data type mismatch in criteria expression" with an OleDbCommand where I have a subquery. 我在其中有一个子查询的OleDbCommand中收到“条件表达式中的数据类型不匹配”。 The actual database is Access although I am not sure it gets as far as presenting the query to the database. 实际的数据库是Access,尽管我不确定它能否将查询呈现给数据库。

DateTime EventDate;
string HT,AT;
int HS,AS;
OleDbCommand cmd

cmd.CommandText = @"INSERT INTO TheTable (EventDate,HT,HS,[AS],[AT]) 
    SELECT top 1 @EventDate,@HT,@HS,@AS,@AT FROM TheTable 
WHERE NOT EXISTS (SELECT 1 FROM TheTable WHERE HT=@HT2)";

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@EventDate", EventDate);
cmd.Parameters.AddWithValue("@HT", HT);
cmd.Parameters.AddWithValue("@HS", HS);
cmd.Parameters.AddWithValue("@AS", AS);
cmd.Parameters.AddWithValue("@AT", AT);
cmd.Parameters.AddWithValue("@HT2", HT);

if I remove the subquery it works fine. 如果我删除子查询,它工作正常。 I am sure all my variables are of the right type and are valid values. 我确信我所有的变量都是正确的类型并且是有效值。 If I take away the subquery it works fine. 如果我拿走子查询,它工作正常。

Is there something about subqueries that makes parameters not work with OleDbCommand? 关于子查询,是否有一些参数无法与OleDbCommand一起使用?

UPDATE: tried the setting the date type and it made no difference 更新:尝试设置日期类型,没有区别

cmd.Parameters.Add("@EventDate", OleDbType.Date); 
cmd.Parameters["@EventDate"].Value = EventDate;

The answer is that the subquery is evaluated first. 答案是首先查询子查询。 Anyone who has used OleDbCommand soon finds out that the name of the parameters does not matter it's the order, which has to match the order of the parameters in the sql. 任何使用过OleDbCommand的人很快就会发现,参数的名称无关紧要,因为顺序必须与sql中的参数顺序匹配。 However, in this case, I guess because the subquery is evaluated first then its parameters have to be supplied first even though they come last in the sql statement! 但是,在这种情况下,我想是因为子查询首先被求值,然后即使其在sql语句中排在最后 ,也必须首先提供其参数!

cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@HT2", HT);
cmd.Parameters.AddWithValue("@EventDate", EventDate);
cmd.Parameters.AddWithValue("@HT", HT);
cmd.Parameters.AddWithValue("@HS", HS);
cmd.Parameters.AddWithValue("@AS", AS);
cmd.Parameters.AddWithValue("@AT", AT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM