当在应用程序的业务逻辑中需要检查一个外键是否有相关的主键时,往往使用select count(*)类型的sql语句。这是一个很显而易的方法,但却不是最快的方法。count(*)函数调用可能会引起对整个表的进行扫描,这是一件很费时的操作。一个更好的方法是使用oracle提供的称为rownum的新特性,使用这个特性可以使数据库只检索一个启示就可以判断主键是否能与外键相配,这比count(*)方法快得多,例如:
sql using count(*)
select count(*) into :ll_count from order where prod_id = :ls_checkprod using sqlca; if ll_count > 0 then // cannot delete product
sql using rownum
select order_id into :ll_orderid from order where prod_id = :ls_checkprod and rownum < 2 using sqlca; if sqlca.sqlnrows <> 0 then // cannot delete product