I have a simple query like so:
SELECT * FROM orders
that returns all orders, simple.
I would like to add optional parameters to my query.
DECLARE @group INT;
SET @group = 1 --IT1
SELECT * FROM orders WHERE group = isnull(@group, group)
This also works fine.
My problem is that i need a second parameter like so:
DECLARE @group INT;
SET @group = 1 --IT1
DECLARE @department VARCHAR(8);
SET @department = 'IT'
SELECT * FROM orders WHERE /*and here add limitation with department*/ group = isnull(@group, group)
My orders table has column GROUP, but no column DEPARTMENT.
Situation looks like so:
I have 2 comboboxes. One for departments, second for group.
In first I have options:
- All
- IT
- CALL CENTRE
Second is populated when user select something from combo1.
If he selects IT the group combo box will have options:
- All
- IT1
- IT2
If user select from first combo department and then group it is easy because I then check only group.
Problem is when he wants all orders from department IT.
Here is how groups are assigned to departments
- IT – 1,2,5
- CALL CENTRE – 4,6
- PRINT – 3
Any ideas?
ADDED:
I have created something like that:
DECLARE @group INT;
SET @group = 1 --IT1
DECLARE @department VARCHAR(8);
SET @department = 'IT'
SELECT * FROM orders WHERE
(@department IS NULL OR (@department='IT' AND group IN (1,2,5)) OR (@department='PRINT' AND group =3))
AND
(@group IS NULL OR group = @group)
I don’t know if it is corrent, it somehow works 🙂
You might pretend you have a table by using CTE populated with records via union all. Then perform a join and a check. If you prefer CTE might be replaced with derived table.