Skip to content
Advertisement

Combine Queries using Union All Dynamically

I have three tables:

I combined those tables using UNION ALL.

My problem is, each year there is a new table to be added. One example is that Table D with corresponding record Order O1-20 and Year 2020. Instead of adding another set of UNION ALL, is there any other way to achieve the same result.

I’m using this to build a report.

Advertisement

Answer

You have 3 options that I can think of:

1) Manually update the union in your query each year – not ideal but probably better than option 2.

2) Use dynamic SQL to build the query and it can automatically build the query based on the date the query is run. Its a bit ugly thought and performance might not be great.

3) This would be my preferred option, run a regular maintenance task to populate a completely separate table, in a single database, with just the data required for the report.


Option 2 might look like:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement