Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 case in joining table

Author  Topic 

mk_garg20
Constraint Violating Yak Guru

343 Posts

Posted - 2004-09-21 : 20:23:54
Hi All,
When i am joining 2 tables, can i use "case" statement in join.

example:-
SELECT .....
FROM table1 inner join table2 on (case when .. then .. end)


thanks


mk_garg

timmy
Master Smack Fu Yak Hacker

1242 Posts

Posted - 2004-09-21 : 20:52:31
Yes you can. It will be slow, though...
Go to Top of Page

mk_garg20
Constraint Violating Yak Guru

343 Posts

Posted - 2004-09-21 : 20:57:57
Allright!
Here are my tables

lodgment
----------
jobnumber
runnumber
amount
type

conract
-------
jobnumber
runnumber

What i want is if lodgment.type is "P" then join on (jobnumber) else (jobnumber and runnumber)

Please tell me what will be syntax.

Thanks

mk_garg
Go to Top of Page

timmy
Master Smack Fu Yak Hacker

1242 Posts

Posted - 2004-09-21 : 21:42:57
Ah - wasn't quite what I had in mind, but here goes:
SELECT L.JobNumber, IsNull(C1.RunNumber, C2.RunNumber) as RunNumber
FROM lodgment L LEFT JOIN conract C1 ON L.jobnumber = C1.jobnumber AND L.type = 'P'
LEFT JOIN conract C2 ON L.jobnumber = C2.jobnumber
AND L.runnumber = C2.runnumber
AND L.type <> 'P'

Or you could do it this way (although I wouldn't recommend...)
SELECT L.JobNumber, C.RunNumber
FROM lodgment L INNER JOIN conract C ON
(CASE WHEN L.Type = 'P' THEN Convert(varchar, L.jobnumber)
ELSE Convert(varchar, L.jobnumber) + ';' + Convert(varchar, L.runnumber)
END) =
(CASE WHEN L.Type = 'P' THEN Convert(varchar, C.jobnumber)
ELSE Convert(varchar, C.jobnumber) + ';' + Convert(varchar, C.runnumber)
END)


Go to Top of Page

mk_garg20
Constraint Violating Yak Guru

343 Posts

Posted - 2004-09-22 : 00:25:51
Thanks Timmy,
It is really helpfull.

mk_garg
Go to Top of Page
   

- Advertisement -