0

我刚刚遇到了这个令人不安的错误。我尝试在 c# 中使用 ODP.NET 执行一个简单的 sql 查询。我按名称传递参数(设置命令的 BindByName=true) 查询使用一个名为“tid”的参数。当我仅将此参数添加到命令的参数集合中时,一切正常。如果我添加另一个未在查询中使用的参数,则查询会崩溃并显示此错误消息

ORA-01036: illegal variable name/number

代码看起来像这样

using( var conn = new OracleConnection([some connection string]) )
{
   conn.Open();
   using( var comm = conn.CreateCommand() )
   {
      // using only the :tid parameter.
      comm.CommandText = "SELECT column FROM Table T WHERE T.Id = :tid";

      comm.CommandType = CommandType.Text;
      comm.BindByName = true;

      comm.Parameters.Add("tid", 500000207);

      // This extra parameter causes an exception when the query is executed.
      // If I remove it everything runs smoothly
      comm.Parameters.Add("param2", "ValueOfSecondParam");

      comm.ExecuteNonQuery();
   }
}

如何传递比查询中实际使用的参数更多的参数,而不会出现异常?(假设我动态创建查询,但我不控制要传递的参数,所以我必须首先传递所有参数)

4

1 回答 1

4

想象一下,您不是将参数提供给 SQL 查询,而是将零件交给试图组装汽车的机械师。假设您正在扮演 Bud Abbott 的那个角色,并且数据库/机制是 Lou Costello:

Abbott:   Alright, Lou, let's get busy putting this car together.  The owner's
          in a big rush.
Costello: Sounds good to me.
Abbott:   Here's the steering wheel.
Costello: Thank you very much.
A:  And here's the engine.
C:  (Ooof!) Oh, thank you SO very much!
A:  And now the first wheel.
C:  That's great.
A:  And now the second wheel.
C:  Looks all nice and shiny with all the chrome, eh?
A:  That's just lovely, Lou.  Oh, here's the third wheel.
C:  I'll just put in back here, behind the driver.
A:  Fine, fine.  And here's the fourth wheel...
C:  Looks great!  I think we're...
A:  And here's the fifth wheel...
C:  Uh, hold on here a minute...
A:  And here's the sixth wheel...
C:  Hang on, Bud, I think we've got a little problem here...
A:  And now the seventh wheel...
C:  Seven wheels?  Seven wheels?!?  WHADDYA MEAN, SEVEN WHEELS!?!?!?
A:  Oh, stop complaining, will you?  Just put it on...
C:  But...
A:  Hurry up now...
C:  But...
A:  ...because here's the eighth wheel.
C:  HEY, ABBBBBOTTTTTTTTTT!!!!!!!

因此,正如您所看到的,提供更多的轮子(或参数)并不是一件很有意义的事情——尽管它可以制作一个很棒的喜剧套路。:-)

分享和享受。

于 2012-09-05T17:17:22.343 回答