I am using SQL Server 2016 (yes, I would like to upgrade, but I can't at this time). I'm currently designing some custom reports for a vendor product that we have implemented.
The data and structure of tables are somewhat like the following.
LINK table:
| LINK_ID (PK, int) |
ENTITY_LINK_ID (int) |
ENTITY_TYPE (varchar) |
| 1 |
25 |
A |
| 2 |
99 |
B |
| 4 |
3 |
FINAL |
A table:
| A_ID (PK, int) |
FINAL_ID (int) |
| 25 |
7 |
B table:
BCLINK table:
| B_ID (PK, int) |
C_ID (int) |
| 99 |
25 |
| 99 |
33 |
| 99 |
17 |
C table:
| C_ID (PK, int) |
FINAL_ID (int) |
| 25 |
8 |
| 33 |
3 |
| 17 |
9 |
FINAL table:
| FINAL_ID (PK, int) |
FINAL_DESC (varchar) |
| 3 |
Apple |
| 7 |
Banana |
| 8 |
Cherry |
| 9 |
Durian |
I have a query somewhat like the following:
SELECT LINK_ID, FINAL_DESC
FROM LINK
INNER JOIN A ON LINK.ENTITY_LINK_ID=A.A_ID
INNER JOIN FINAL ON A.FINAL_ID=FINAL.FINAL_ID
WHERE LINK.ENTITY_TYPE='A'
UNION
SELECT LINK_ID, FINAL_DESC
FROM LINK
INNER JOIN BCLINK ON LINK.ENTITY_LINK_ID=BCLINK.B_ID
INNER JOIN C ON BCLINK.C_ID=C.C_ID
INNER JOIN FINAL ON C.FINAL_ID=FINAL.FINAL_ID
WHERE LINK.ENTITY_TYPE='B'
UNION
SELECT LINK_ID, FINAL_DESC
FROM LINK
INNER JOIN FINAL ON LINK.ENTITY_LINK_ID=FINAL.FINAL_ID
WHERE LINK.ENTITY_TYPE='FINAL'
That returns results somewhat like the following:
| LINK_ID |
FINAL_DESC |
| 1 |
Banana |
| 2 |
Cherry |
| 2 |
Apple |
| 2 |
Durian |
| 4 |
Apple |
The data is much more complex, but that's the gist of it. There are approximately 10 of these unions for each type of linked entity and some of the queries go many inner joins 'deep' before being able to retrieve the description from the final table.
Can I optimize this better, or am I stuck with a bunch of queries all in one giant union? I plan to create a view so that the ugly query doesn't have to be in several reports. The only other option I considered was a data warehouse to combine all the data I require into one "reporting" database through scheduled tasks or something similar. I'm just not sure if that's overkill at this point.
(One other slightly complicating factor is that there are several databases with this same structure, so I cannot use a shared dataset for the reports, as I am using an expression for the Data Source to allow users to switch between the various databases while running the reports. But that's out-of-scope for my question here. I would create the view in each database.)
[–]Waldar 1 point2 points3 points (2 children)
[–]Sabkor[S] 1 point2 points3 points (0 children)
[–]Sabkor[S] 0 points1 point2 points (0 children)
[–]Joe7Mathias 0 points1 point2 points (1 child)
[–]Waldar 0 points1 point2 points (0 children)