Case in Join

  • Thread starter Thread starter tshad
  • Start date Start date
T

tshad

Can you put a Case statement in a Join?

My problem is that I have 2 possible fields I want to join to the same
table. If one is null, use the other.

For example:

Create Table Position
(
UserID1 int,
UserID2 int
)

Create Table Logon
(
UserID int,
UserName
)

I want to do something like (I know this doesn't work, but you should get
the idea of what I am looking for from it).

Select UserName From Position P Join on Logon L (CASE WHEN UserID1 is not
null Then (P.UserID1 = L.UserID) ELSE (P.UserID2 = L.UserID) END)

I am trying to get the User Name from UserID1, unless it is null. If that
is the case, then get the User Name from UserID2.

Thanks,

Tom
 
Check out the coalesce() in SQL

Your SQL would be something like "on coalesce(p.UserID1,p.UserID2) = L.UserID"
 
Try this and assume Logon.UserName is VARCHAR:

select l.username
from logon l
join (select isnull(userid1,userid2) userid
from position) vt
on l.userid = vt.userid

-Sydney
 
Try this and assume Logon.UserName is VARCHAR:

select l.username
from logon l
join (select isnull(userid1,userid2) userid
from position) vt
on l.userid = vt.userid

-Sydney
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top