Saturday, February 25, 2012

Query building based on user selections

I currently have a form that has different options in a list box such as:

Status Codes

Division Codes

Project Managers

Report Types

The user can select a value from any one of these and hit a search button to run a query. Currently I am running through some IF statements to evaluate which combination of values were selected to run the right SQL code. Example

A user wants to view reports that have a status code of "Active" and a division code of "001". So my if statement would be something like (not in perfect syntax, just trying to get the point across):

if strStats <>"" and strDivision <>"" and strProjMgr ="" and strRptType ="" thenselect ...from ...where status_cd = strStats and division_cd = strDivision
end if
So my question is this: Is there a way to build the query dynamically (1 time) without having to run through all the senarios? 

Yes. you could write a query as:

select ...
from ...
where status_cd = ISNULL(@.strStats,status_cd)

and division_cd = ISNULL(@.strDivision,division_cd )

and ...

pass the values for @.strStats and @.strDivision. You can pass the parameters in any combination.

|||So this basically allows a condition to be null or a value can be passed?|||Yes.

No comments:

Post a Comment