I want to create a table-valued function that filters Table1 based upon values in Table2 but apply NO filtering if Table2 contains nothing.
I'm not good at SQL, so this is what I have thus far:
CREATE FUNCTION MyFunction(@table2 Table2 READONLY)
RETURNS TABLE
AS RETURN (
SELECT userID, first_name, last_name
FROM Table1
WHERE EXISTS (SELECT user_ID FROM Table2 WHERE user_ID = Table1.user_ID AND user_security_group = 5)
)
In the above case, the function should return all users and their first/last names if they are in the user_security_group 5.
But if NO users exist within the user_security_group 5, I want to return ALL users (i.e. apply no filtering). So, pseudo code like:
CREATE FUNCTION MyFunction(@table2 Table2 READONLY)
RETURNS TABLE
AS RETURN (
SELECT userID, first_name, last_name
FROM Table1
-- pseudo code here
IF WHERE EXISTS (SELECT user_ID FROM Table2 WHERE user_ID = Table1.user_ID AND user_security_group = 5)
-- THEN APPLY FILTERING
-- ELSE DO NOT APPLY FILTERING
)
How do I achieve the desire functionality within MyFunction? Thank you.
P.S. - the above example is the simple case. Ideally, I'll be passing multiple tables as parameters into MyFunction and apply the same IF/ELSE logic to each parameter table.