5

我正在使用.net 的 Oracle 数据访问,我的查询是

command.CommandText = "select * from table1 where expirydate =:EXPIRYDATE";
command.Parameters.Add("EXPIRYDATE", OracleDbType.Date, DateTime.Today,ParameterDirection.Input);

var results = command.ExecuteScalar();

我收到以下错误“ORA-00932:不一致的数据类型:预期的日期有 NUMBER”

如果我将查询更改为:

command.CommandText ="select * from table1 where expirydate =
to_date(:EXPIRYDATE,'DD/MM/YYYY')";

我没有得到任何结果。

提前致谢。

4

2 回答 2

15

Most likely reason for this error is that the order of the parameters in your query does not match the order you add them to the Parameters collection. Oracle Data Access pretends to bind them by name, but actually binds them by order.

于 2014-07-16T13:41:08.897 回答
9

如果您使用的是 ODP.NET,OracleCommand 应该有一个 BindByName 属性,它将强制命令按参数名称而不是顺序来绑定参数。

const string sql = @"select :parameter2, :parameter1 from dual";

using (var cmd = new OracleCommand(sql, conn))
using (cmd.Parameters.Add(":parameter1", "FOO"))
using (cmd.Parameters.Add(":parameter2", "BAR"))
using (var reader = cmd.ExecuteReader()) {
    reader.Read();
    // should print "FOOBAR"
    Console.WriteLine("{0}{1}", reader.GetValue(0), reader.GetValue(1));
}

using (var cmd = new OracleCommand(sql, conn) { BindByName = true })
using (cmd.Parameters.Add(":parameter1", "FOO"))
using (cmd.Parameters.Add(":parameter2", "BAR"))
using (var reader = cmd.ExecuteReader()) {
    reader.Read();
    // should print "BARFOO"
    Console.WriteLine("{0}{1}", reader.GetValue(0), reader.GetValue(1));
}

这会带来轻微的性能损失,但在大多数情况下它可能小到可以忽略不计。

于 2014-07-17T19:52:32.113 回答