在 PL/SQL 中使用游标方法与开始-结束-异常方法进行单行查询的优缺点
每当在 PL/SQL 中编写只需要一行的查询时,通常有两种方法来完成:
- 使用隐式 SELECT INTO,并检查 TOO_MANY_ROWS 和
NO_DATA_FOUND
异常。 - 使用显式游标并仅从游标中获取第一行。
尽管这两种方法产生相同的结果,但这些方法的优缺点是什么?
Whenever a query in PL/SQL is written where only one row is expected, there are two ways it is often done:
- Use an implicit
SELECT INTO
, and check forTOO_MANY_ROWS
andNO_DATA_FOUND
exceptions. - Use an explicit cursor and just fetch the first row from the cursor.
Though both the approaches yield the same result, what are the pros and cons of these approaches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 select 语句预计只返回一行时,“SELECT INTO”是更好的方法。是的,许多开发人员更喜欢使用游标并只获取一行,因为这样可以省去处理 NO_DATA_FOUND 的“麻烦”——也就是说,他们将问题掩盖起来,给用户留下一个神秘的错误。我最近在博客中讨论了这种不良做法*。
(* 这是一种糟糕的做法,遗憾的是,这种做法常常被纳入项目 PL/SQL 标准中!)
至于计数然后查询,这只会使工作量增加一倍,因此也应该避免。
When a select statement is expected to return exactly one row then a "SELECT INTO" is the better approach. Yes, many developers prefer to use a cursor and fetch only one row because it saves them the "bother" of dealing with NO_DATA_FOUND - i.e. they sweep the problem under the carpet and leave the user with a mysterious bug. I blogged about this bad practice* recently.
(* a bad practice that is often sadly enshrined in project PL/SQL standards!)
As for counting and then querying, that just doubles the work so is to be avoided too.