473,418 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,418 software developers and data experts.

Joining to different tables based on a condition

Hey Troops,

I'm not sure if this is allowed, but I'm trying to keep my SP generic and reduce duplicate code. Depending on a condition, I need to JOIN to different tables, which slightly changes the result set. So, I would include conditions later to grab the proper fields based on checking the same condition (@TravelType = 'A').

Here's a sample of what I'm doing, which is currently giving me a syntax error near 'CASE':


CASE WHEN @TravelType = 'A'
THEN
LEFT JOIN AirportCity DepCity
ON DepFrom = DepCity.Code

LEFT JOIN AirportCity ArrCity
ON ArrTo = ArrCity.Code
ELSE
LEFT JOIN City DepCity
ON DepartureAirportCode = DepCity.CityCode
AND DepCity.TypeCode = 'R'

LEFT JOIN City ArrCity
ON ArrivalAirportCode = ArrCity.CityCode
AND ArrCity.TypeCode = 'R'
END

Can someone shed some light on why this throws an error? Or, is there another way to accomplish such?

Thanks!
Feb 18 '10 #1
12 51406
ck9663
2,878 Expert 2GB
Try something like this...

Expand|Select|Wrap|Line Numbers
  1.  
  2. FROM YourMainTable
  3. LEFT JOIN AirportCity DepCity ON @TravelType = 'A' and DepFrom = DepCity.Code
  4. LEFT JOIN AirportCity DepCity ON @TravelType = 'B' and SomeOtherColumn = SomeOtherColumnFromSomeOtherTable
  5.  
  6.  
Happy Coding!!!

~~ CK
Feb 18 '10 #2
Is that putting the condition within the ON clause? So, it will only do the first JOIN if @TravelType = 'A' and only do the second JOIN if @TravelType = 'B'?
Feb 18 '10 #3
I see other examples like that, but the @TravelType in our case would need to be a field in the table being joined to. @TravelType is just a local variable. But if you're saying it'll work, I'll give it a shot.
Feb 18 '10 #4
Delerna
1,134 Expert 1GB
It actually does both joins but only one of the joins will return any records because @TravelType will be either 'A' or it will be 'B'

Nice approach CK
you may need a case in your select clause so it will select the appropriate field based on the value of @TravelType
Feb 18 '10 #5
Ok, so you can put a condition in the 'ON' clause... not just the columns to link on? Slick. We actually found another way to get what we need, but I did learn something. Thanks much for your time fellas.
Feb 18 '10 #6
ck9663
2,878 Expert 2GB
Yes you can.

You can even do an always true condition like ON 1 = 1 to pair each record on your main table to every single record on your joined table. This is specially helpful if you need a sequence of some sort for every record in the main table.

So make sure about your conditions...

Happy Coding!!!

~~ CK
Feb 18 '10 #7
HKNew
2
@stretchtack
I have also got a similar issue. Need to have a conditional JOIN. I tried with CASE statements but I got syntax error near CASE.
Eg:
IF @Type=A, then I need to JOIN with tableA and get TableA.Name
IF @Type=B, then I need to JOIN with tableB and get TableB.Name
IF @Type=C, then I need to JOIN with tableC and get TableC.Name

Can someone help me out in this.
Jun 22 '10 #8
Delerna
1,134 Expert 1GB
Post the code that is giving you the error
Jun 23 '10 #9
HKNew
2
Here is the code..
CREATE PROCEDURE GetDetails
@input1 AS VarCHAR(50) = '',
@inputGuid AS UniqueIdentifier
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY

SELECT

[FinalTable].[Name1] AS 'Name1',
[FinalTable].[Name2] AS 'Name2',

FROM MainTable

CASE [MainTable].[Type]
WHEN 'A' THEN
INNER JOIN [TableA] [FinalTable] ON [MainTable].[Id] = [FinalTable].[Id]
WHEN 'B' THEN
INNER JOIN [TableB] [FinalTable] ON [MainTable].[Id] = [FinalTable].[Id]
END
WHERE [MainTable].[Id1] = 1

END TRY
BEGIN CATCH
--Rethrow the error.
END CATCH

SET NOCOUNT OFF
END

Based on the type (A or B), the JOIN has to be formed. If the type is 'A' then JOIN should be only with TableA and not with TableB.Similarly if type is 'B' then should be only with TableB.

The columns, "Name1" land "Name2" should be selected from either of these two tables based on the type.
Jun 23 '10 #10
Delerna
1,134 Expert 1GB
Can you explain what [FinalTable] is.

I am asssuming that you mean it as an alias

If that is the case then
this seems more appropriate but I am only guessing at what you are trying to do
Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.    CASE WHEN [MainTable].[Type]='A' THEN
  3.       [TableA].[Name1] ELSE [TableB].[Name1]
  4.    END
  5.    AS 'Name1',
  6.    CASE WHEN [MainTable].[Type]='A' THEN 
  7.       [TableA].[Name2] ELSE [TableB].[Name2]
  8.    END
  9.    AS 'Name2',
  10. FROM MainTable
  11. LEFT JOIN [TableA] ON [MainTable].[Id] = [FinalTable].[Id]
  12. LEFT JOIN [TableB] ON [MainTable].[Id] = [FinalTable].[Id]
  13.  
  14.  
Jun 23 '10 #11
Delerna
1,134 Expert 1GB
Incidentally you cannot do conditional joins like that.
You cannot include the table to join in the true/false parts of the case.
The two tables to join must be outside the case altogether and only the joining fields can be inside.
I hope that makes sense
Expand|Select|Wrap|Line Numbers
  1. SELECT  *
  2. FROM theTable a
  3. JOIN theOtherTable b on a.field = 
  4.    CASE WHEN Condition=True THEN
  5.      b.TrueJoinField ELSE b.FalseJoinField
  6.    END
  7.  
Jun 23 '10 #12
ck9663
2,878 Expert 2GB
You can include other conditions in your JOIN, not just relational. Try something like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.  
  4. SELECT
  5. Name =
  6.    case 
  7.       when MainTable.Type = 'A' then [FinalTableA].[Name1] 
  8.       when MainTable.Type = 'B' then [FinalTableB].[Name1]
  9.       else NULL
  10.    end
  11. FROM MainTable
  12.    left join [TableA] [FinalTableA] ON [MainTable].[Type] = 'A' and [MainTable].[Id] = [FinalTableA].[Id]
  13.    left join [TableA] [FinalTableB] ON [MainTable].[Type] = 'B' and [MainTable].[Id] = [FinalTableB].[Id]
  14. WHERE [MainTable].[Id1] = 1
  15.  
  16.  
Happy Coding!!!

~~ CK
Jun 24 '10 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: sdowney717 | last post by:
Select LOCGeneralHave.LSCH, LOCSubClassHave.LSCH from LOCGeneralHave , LOCSubClassHave Where (LOCGeneralHave.LCNT <> '0' and LOCSubClassHave.LCNT = '0') This query seems to be ignoring the...
10
by: Marizel | last post by:
I'm not sure there's an easy solution to this, but thought I'd ask. I often find myself with a query which I'd like to reuse, but with a different datasource. These datasources generally have...
20
by: Dennis Gearon | last post by:
I am working on a design where a location for something can have: Fully qualified address with even building names, room numbers, and booth numbers. **-OR-** GPS location **-OR-** Both ...
2
by: Coquette | last post by:
Hi all. I'm new here. I wanted to ask your opinion about *joining two tables* from *two different database* together. Is *that* possible? My project requires me to join identical tables from...
3
by: Reader | last post by:
Hello all, I am joining two tables in a query and the output should be all those records where two fields in table1 match two corresponding fields in table2. I joined the tables using both...
1
by: EyesFriedOpen | last post by:
I was trying to post this to the IBM DB2 forum, however I do not have the "New Post" button available when I view the IBM DB2 forum. Therefore, I apologize if this is not the right place for this. ...
1
by: regikutty | last post by:
im a begginer,im using sql server 2005 i have 3 different tables Customer table intcid Companyname ProjectTable
4
by: Cyprus106 | last post by:
Apparently, Im incapable of properly executing this query! I've been at this for far too long and gotten nowhere. Forgive me if this is a umb mistake; I'm not great at SQL. I've got three tables,...
0
by: bscott | last post by:
I'm sure there is a simple solution to this, but being fairly new to Access I would appreciate some assistance... I have a query that joins two tables. One table has call details for each day...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.