Dynamic query conditions are frequently encountered in reports, such as a drop-down list with time, "all", "Morning", and "Afternoon ". If you want to query the data of all time periods, select all. How can you write this statement without using a stored procedure?
I have made 7 or 8 such reports recently. I will write them down for reference later.
When the condition is all input, all the program and site are displayed. At this time, no fixed SQL statement can be written, but the SQL statement must be spliced according to the condition.
The following is the query method in the dataset. Note that the equal sign before the SQL statement must be written.
= " SELECT site, sum(plan_qty) plan_qty, sum(actual_qty) actual_qty, sum(var) qty_variance, avg(plan_qty) avg_plan,stddev(plan_qty) stddev_plan, count(1) combs, status from ( " & " SELECT a.site, a.hsa_part_no, a.media_part_no, sum(plan_qty) plan_qty, sum(actual_qty) actual_qty, sum(actual_qty) - sum(plan_qty) var, " & " CASE WHEN (sum(actual_qty) - sum(plan_qty)) < 0 THEN 'UNDER' " & " WHEN (sum(actual_qty) - sum(plan_qty)) = 0 THEN 'MATCH' " & " WHEN (sum(actual_qty) = 0 AND sum(plan_qty) = 0) THEN 'NO BUILD' " & " WHEN (sum(actual_qty) <> 0 AND sum(plan_qty) = 0) THEN 'NO PLAN' ELSE 'OVER' END Status " & " FROM HM_SUMM_COMBO a " & " WHERE (DAY_ID >= to_char(sysdate - 5,'YYYYMMDD') AND DAY_ID <= to_char(sysdate + 2,'YYYYMMDD')) " & iif(Parameters!Program.Value = "ALL"," "," AND a.PROGRAM = '" & Parameters!Program.Value & "'") & " " & iif(Parameters!Site.Value = "ALL"," "," AND a.SITE = '" & Parameters!Site.Value & "'") & " " & " GROUP BY a.SITE, a.HSA_PART_NO, a.HSA_DESC, a.MEDIA_PART_NO )c " & " GROUP BY c.SITE, c.status "
Note:
IIF (parameters! Program. value = "all", "", "and A. program = '" & parameters! Program. Value &"'")&""
Based on the parameter value, the SQL statement concatenates different statements. When the value is all, it is equivalent to an empty string, that is, there is no condition!