Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
select * from table1 inner join (case when id=1 then table2 else table3 end)tbljoin
on tbljoin .id=table1.id
Posted
Updated 23-Feb-14 19:38pm
v2
Comments
Bernhard Hiller 24-Feb-14 2:50am    
Is that "id=1" somehow related to table1.id?

Hi Mukesh,

I Do not know whether its optimal solution or not,
but for sure this will work for

You can compose the query like the one below
SQL
DECLARE @query VARCHAR(MAX);
--Beginning part of the query
SET @query = 'SELECT * FROM table1 INNER JOIN ';

--Get ID from the table
SELECT  @ID = ID FROM table1 WHERE BLAH-BLAH = BLAH-BLAH;
--With respect to ID table name is set to the query
IF (@ID = 1)
SET @query += 'table2 ';
else
SET @query += 'table3 ';

--Final part of query
SET @query += 'ON tbljoin.id=table1.id';

--Now execute the query
exec(@query);

Hope this help you a bit.

Regards,
RK
 
Share this answer
 
v4
Comments
phil.o 24-Feb-14 9:06am    
You should put a whitespace between 'table2'/'3' and 'ON tblJoin.id'; otherwise there will be a great syntax error message.
Moreover, there is still a typo in the last part (ON tblJoin is repeated twice).
♥…ЯҠ…♥ 24-Feb-14 9:08am    
Thanks phil.o for pointing that ;)
phil.o 24-Feb-14 9:24am    
You're welcome ;)
Assuming the 3 tables are of the same structure:
SQL
SELECT * FROM table1 JOIN table2 ON table1.id=table2.id WHERE table1.id=1
UNION
SELECT * FROM table1 JOIN table3 ON table1.id=table3.id WHERE table1.id=2
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900