I have a database table named call with columns call_time, location, emergency_type and there are three types of emergency: paramedics, police and firefighters. In the windows form I created CheckBoxes ‘paramedics’, ‘police’, ‘firefighters’ and I want to retrieve all table columns which meet user’s selection.
I created a function:
public static DataTable GetHistory(DateTime from, DateTime to, bool paramedics, bool police, bool firefighters) { string select = 'SELECT call_time, location, emergency_type where call_time between @from AND @to AND'; if(paramedics) { select += ' emergency_type = 'paramedics' '; } if(paramedics && police) { select +=' emergency_type = 'paramedics' OR emergency_type = 'police'; } ... }
This code however seems very dirty because if there were 30 kinds of emergency there would be 30! combinations and I would get old before writing all if statements.
I would appreciate if you shared your practice for retrieving data that meet the selected search conditions if there are many options you can chosse.
Thanks!
Well if you have to use emergency_type as a string then instead of passing in bools you could send in a List containing the text representation of the emergency type. For example to adjust the above code you could change the method signature to
and then pass in a list that looked like these (for example)
Then you could adapt your query to use the SQL IN statement in your where clause. Next convert the list of strings into a comma separated string like
A simple way to create the values variable is to use
By the way you could use a parameterized command to avoid SQL injection. Once you have the string you can simply do