I need to create a view using data in a table for the table name and column name. Preferably I’d like to do it with set processing. I have a sample of doing this for one record in the table with a script of stored procedure, which won’t do for the application. The resulting view pulls data from a data logger for display on a dashboard, so it needs to be current and fast. That’s why I think a view would work best, but I’m having trouble coming up with the SQL.
I have a table that looks like the following. This is an example of two records, there are tens of thousands of them. There will be one or more duplicate table names, which corresponds with one or more column names in the LOGGER_FIELD column.
From data in this table, I’d like to create a view that would have this sql:
select TmStamp, site_id, value
from
(select TmStamp, G0025890, G0025891
from [BIG SLOUGH (STN 953)_HOURLY]
where TmStamp = (select max(TmStamp) from [BIG SLOUGH (STN 953)_HOURLY])) p
unpivot
(value FOR site_id IN (G0025890, G0025891))AS unpvt;
The table [BIG SLOUGH (STN 953)_HOURLY] looks like:
The table name in the FROM is tabname in the view, and the values in LOGGER_FIELD are the column names. The ending view will look like:
Best Answer
You can use a dynamic query.
dbfiddle here