February 19, 2014 at 5:39 am
SELECT t1.id,name, from table1 t1 INNER join table t2 on t1.id=t2.pid
case when type='A' then
Inner join table3 t3 on t1.id=t3.id
else
Inner join table4 t4 on t1.id=t4.id
END
February 19, 2014 at 5:44 am
That's not possible in SQL.
You need to write two seperate queries and choose between them using an IF statement, or you construct your query dynamically and execute it with sp_executesql.
Need an answer? No, you need a question
My blog at https://sqlkover.com.
MCSE Business Intelligence - Microsoft Data Platform MVP
February 19, 2014 at 6:53 am
As Koen mentioned that is not possible in SQL and should explore the options he mentioned.
Probably one more option if i understand your question correctly is to do a LEFT JOIN as below. Try if this helps...
SELECT T1.Id,T2.Name,
CASE WHEN T1.Type = 'A' THEN T3.SomeColumn
ELSE T4.SomeColumn
END AS SomeColumn
FROM Table1 AS T1
INNER JOIN Table2 AS T2 ON T1.Id = T2.Pid
LEFT OUTER JOIN Table3 AS T3 ON T1.Id = T3.Id AND T1.Type = 'A'
LEFT OUTER JOIN Table4 AS T4 ON T1.Id = T4.Id AND T1.Type <> 'A'
February 23, 2014 at 6:14 pm
Perhaps something like this might work for you:
SELECT t1.id,name
FROM table1 t1
INNER JOIN table t2 ON t1.id=t2.pid
INNER JOIN table3 t3 on t1.id=CASE type WHEN 'A' THEN t3.id ELSE t1.id END
INNER JOIN table4 t4 on t1.id=CASE type WHEN 'A' THEN t1.id ELSE t4.id END
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply