Skip to content
Advertisement

SQL Server – Create view using many fields of a row as names of columns

I present to you a simple and short example of what I want to resolve.

I need to create a view from two tables.

tables

The table indicator stores in a single row the names of the indicators to be measured by the system.

The table sample stores the values of the measurements.

The view I want to make has to look like this: views

Is there any way to do this?

Note: The indicators can be more than 100, and can be modified on the way. The solution should be dynamic: SELECT Indicator1 AS 'Temperature' is not an option

I appreciate your comments very much.

Best regards!

Advertisement

Answer

As @Neil and @Sean have both recommended this is only possible via dynamic sql which can be executed within a stored procedure.

As such below is an example of said stored procedure with produces the asked for result (the procedure itself creates and drops the sample tables and data, however you can remove those sections to fit your needs)

This can then be called with this syntax

Which dynamically names the columns based on the parameter passed in.

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