Skip to content
Advertisement

SQL method for returning data from multiple tables based on column names

I am trying to do something a little weird and cannot figure out the right method for getting it done. Essentially I am trying to pull all tables/views and columns where the column name is like some string. In addition to that I would like to pull 1 row of data from that table/view and column combination. The second part is where I am lost. I know I can pull the necessary tables/views and columns with the below select statement.

So that I get something like the below

But I want to get something like this:

Can anyone offer any insight?

Advertisement

Answer

I can’t think of a simple way to do this within a query, but here’s one option…

Put the list of the columns and tables into a temp table and run them through a loop, using dynamic SQL to select the max row for each.

I’ve added plenty of comments below to explain it.

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