refactoring PL/SQL
I encountered the following PL/SQL code(variables modified) at work:
PROCEDURE test(i_w IN a.w%type,o_result IN OUT resu_cur_type) IS
BEGIN
IF i_w IS NULL THEN
open o_result for SELECT a.x, b.y FROM a,b WHERE a.z=b.z;
ELSE
open o_result for SELECT a.x, b.y FRO开发者_JAVA百科M a,b WHERE a.z=b.z AND a.w=i_w;
END IF;
END test;
I think the above is equivalent to the following:
PROCEDURE test(i_w IN a.w%type,o_result IN OUT resu_cur_type) IS
BEGIN
open o_result for SELECT a.x, b.y FROM a,b WHERE a.z=b.z AND NVL(a.w,1)=NVL(NVL(i_w,a.w),1);
END test;
Won't it be the same?. Could somebody please explain is there any reason to use the original version?. Please note that the original cursor is a 50 line query, so refactoring might improve its readability and keep it simple.
Edit:
To address the problem in Kevin Burton's answer, I've updated the WHERE condition.
As Kevin Burton said, your new query is not equivalent. This is though:
PROCEDURE test(i_w IN a.w%type,o_result IN OUT resu_cur_type) IS
BEGIN
open o_result for SELECT a.x, b.y FROM a,b
WHERE a.z=b.z
AND (i_w IS NULL OR a.w=i_w);
END test;
However, the original code may be more efficient as can use an index on a.w when i_w is not null but do something different when it is null - i.e. it tailors the query to the parameters used.
if a.w is null you will not select the records
as
a.w=NVL(i_w,a.w);
will be
a.w=NULL
精彩评论