I am doing a fairly complex SQL query due to the unnormalized nature of the system database. The query flow is as follows.
I make one SELECT
of some fields from several tables that I join .
Then, depending on the value of one of these fields, (A,B,C,D)
I have to join with another table. For example, if it is type 'A'
the Join will be against CabecerasA
, if it is it 'B'
will be against CabecerasB
and so on.
I want to use a Switch Case
, but I wouldn't know how to implement it. I put an example query:
SELECT id , att1 , att2 , tipo
FROM Table1 inner Join Table2 on(...)
inner Join Table3 on(...)
According to the value of the attribute , 'tipo'
I must join this query with the corresponding table.
How should I apply my Switch Case
?
Quick answer: You can't. The CASE works at the data/column level, it does not participate in the FROM/JOIN. What you want to do is basically multiple LEFT JOINs depending on the value of each field
tipo
I mean, you can't escape adding all the corresponding left joins to each
tipo
unless... you use separate queries and join them using the UNIONDepending on the data, one form may be more "performing" than another.
One way to solve it is to generate a query dynamically, that is, the query is formed according to all those conditions that you want to have:
In the example that I am giving, you would be receiving a
tipo A
, for which the output of the generated script would be the following: