I originally posted this on devshed. But I noticed that it is dead silent over there. I am not sure whether anything would happen over there. So my apologies for the crosspost.
I was asked to come up with a solution for a SELECT on multiple columns. I have not seen the database, so I don’t know whether it is structurally faulty or could be optimized in one way or another. Anyway, the situation is as follows:
in the first scenario there is a table with multiple columns that hold numeric data. The query ought to return the max value of each mentioned column just like
Code:
SELECT MAX(col1), MAX(col2), … , MAX(coln) FROM table
As there are many (I was told 200) columns this would require to state each column in the MAX(colx) part of the statement.
I would imagine there is a way of retrieving the column names and then looping through the result. Thus saving to state each and every column name. All the solutions I have found or thought of do just that.
And as if that was not enough. Scenario 2 and 3: What if there were also mutliple tables or multiple databases with the same task to find the max values?
I am so delighted to see you round here. Your answers on my few questions on devshed were always a great help.
I am already able to pull the column names from the INFORMATON_SCHEMA:
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = ‘table’
ORDER BY ordinal_position;
In other cases I am building my query in Excel concatenating the various values. I was hoping that there could be a more elegant solution. But you are right, if it is prepared once, it can easily be reused once the need arises.