To simplify the description, I'll use a member table and a mail table. The mail table has the following structure:
-------------------------------
FromMember int NOT NULL (FK)
ToMember int NOT NULL (FK)
...
-------------------------------
I want to write a query which will return all the mail for a particular member whether he is the FromMember or the ToMember. That's easy just use an OR clause in the WHERE clause.
But where it gets complicated is that I want to join the mail table to the member table to retrieve the member info for the other member. So if I'm the FromMember than the join clause to the member table would use the ToMember field and if I'm the ToMember than the join clause would use the FromMember field. Basically, the ON clause needs to join with two different fields based on a specific condition. Is that possible?
My solution so far is to use UNION ALL as follows:
SELECT * FROM mail INNER JOIN member ON mail.ToMember = member.MemberID
WHERE mail.FromMember = @me
UNION ALL
SELECT * FROM mail INNER JOIN member ON mail.FromMember = member.MemberID
WHERE mail.ToMember = @me
However, I would like to put this query in a view because the resultset will be used in many places in my code. That means that I would need a parametrized view which I think I need to implement using a User-Defined Table Function.
Basically, I'm looking for two answers:
Is there a better way to write that query instead of UNION ALL?
And should I put that query in a VIEW or a UDF?
If VIEW is the preferred method, how can I pass the @me parameter to the VIEW. I cannot move the @me param to the WHERE clause has some people have said in their answers because the WHERE clause depends on the ON clause. Pulling out the WHERE clause and then ORing them will not return the same resultset as the above UNION ALL query.