Oracle. Select all if parameter is null else return specific item issue

后端 未结 3 1058
自闭症患者
自闭症患者 2021-01-26 05:43

I need to return all records if input parameter is null.

I\'ve written a simple query

declare  
   l_sql varchar2(100);
   i number := 1;
 begin
   l_sq         


        
3条回答
  •  清歌不尽
    2021-01-26 06:23

    Please let me show the full story behind the Val's question.

    We need to produce the report from the Job table which has following fields :

    • Id not null,
    • JobNumber not null,
    • JobDate not null,
    • MissedReasonId null,
    • FollowUpReasonId null ....

    The report filter form produces the input parameters for the report stored procedure.

    Among other parameters there are two check list boxes on that filter form to check the required Missed Reason items or/and FolowUp Reason items.

    As you can see MissedReasonId and FollowUpReasonId are nullable therefore if user doesn't check any item in those check list boxes we need to show all the jobs.

    If some of the items are checked we send them to the stored procedure as a delimited ID list.

    We are trying to get the data using one single query.

    The assumption is :

    • If Id list input parameter is empty I don't want Oracle to check if the value of (lets say) MissedReasonId is in the provided delimited list (MissedReasonIdList).
    • If Id list is not empty lets select only those records which have MissedReasonId value in the provided list.

    There's no problem with the ID list itself. We can convert it into table or an array and make selection working fast enough. There's no problem if the ID list is mandatory on the filter form (we don't need to check the parameter for null). The problem arises then it is not mandatory (parameter can be null) and there are multiple filter conditions like that on the filter form.

    The query we are using looks like this :

    Select j.Id , j.JobNumber  .....
      From Job j
      left join MissedReason mr on mr.ID = j.MissedReasonId 
      left join FollowUpReason fr on fr.ID = j.FollowUpReasonId
      ....
      Where
        (j.JobDate between P_StartDate and P_EndDate)
        and ( P_MissedReasonIdList is null or (j.MissedReasonId "IS IN THAT P_MissedReasonIdList"))
        and ( P_FollowUpReasonIdList is null or (j.FollowUpReasonId "IS IN THAT MissedReasonIdList"))
        and ......
    

    We expected that if an input parameter is null in the first part of the WHERE condition :

    "and ( P_MissedReasonIdList is null or (j.MissedReasonId "IS IN THAT P_MissedReasonIdList"))"

    Oracle shouldn't bother to check the second part of the condition. (This is what Val mentioned in his question. Right Val ?)

    I really don't want to build the dynamic query on the fly including only those conditions which should be checked into query.

    But is there any other solution to our problem ?

提交回复
热议问题