Skip to content
Advertisement

Loop query through multiple tables

I would like to the same query which should almost never return any results through multiple tables. The table name is the same except with the addition of the year. So my query looks like this:

and I would like to loop through all the years from 2001 to 2020. So it should look like this:

If there are results they can be stored in a temp table. I thought of creating a loop with the table names or creating dynamic sql query. What is the best practice and how can I use this query for all the tables just by executing it once?

Thank you!

Advertisement

Answer

To reiterate my comment:

This sounds like a denormalisation problem, really you should have 1 table with a column for the year.

Really, you should be fixing your design.

Anyway, onto the problem: You can do this with dynamic SQL, yes, but you’d be better off fixing the design. This however, create and executes the statement dynamically. i’ve used FOR XML PATH due to a lack of version tag:

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