Reputation: 13
Below is what I am trying to achieve. I have a procedure which receives employeeIds as optional arguments and stores them into a temp table (temp_table) like this
empId
-------
3432
3255
5235
2434
Now I need to run below query in 2 conditions:
1st condition: if argument is non blank then my query should be-
SELECT *
FROM DEPARTMENTS
INNER JOIN temp_table ON emp_no = empId
2nd condition: if argument is blank it will take all the rows from department table
SELECT *
FROM DEPARTMENTS
One option I can use is:
IF (@args <> '')
BEGIN
SELECT *
FROM DEPARTMENTS
INNER JOIN temp_table ON emp_no = empId
END
ELSE
BEGIN
SELECT *
FROM DEPARTMENTS
END
But I am looking for a better option where I don't need to write almost same query twice. Please help.
Upvotes: 1
Views: 34
Reputation: 44951
I recommend to stick to what you are already doing.
It is the cleanest and safest way performance wise.
Upvotes: 3
Reputation: 6729
Try this one
SELECT *
FROM DEPARTMENTS
WHERE (
@args <> ''
OR EXISTS (SELECT 1 FROM temp_table WHERE emp_no = empId)
)
Upvotes: 1