Question

Is it possible to create a view (not stored procedure) with dynamic column names based on another table? For example:

Code:
CodeId|Description
------------------
     1|Title
     2|Notes

Data:
DataId|Content|CodeId|GroupId
-----------------------------
     1|Title1 |     1|      1
     2|Note1  |     2|      1
     3|Title2 |     1|      2
     4|Note2  |     2|      2

Select Result:
GroupId|Title |Notes
-------------------
      1|Title1|Note1
      2|Title2|Note2

The column names "Title" and "Notes" would come from the Code table. I'm guessing the answer is no, but would like to confirm. Thanks!

Edit: I understand how this could be "dangerous". If someone updates the code description the view would change, breaking any SQL dependent on the column names. In that case I could use the CodeId instead, which would not be allowed to change.

Was it helpful?

Solution

The perils of the EAV (Entity-Attribute-Value) model are many, and you're just setting yourself up for a ton of headaches in the future. With that said, your specific question seems possible to solve to me. You've been warned though...

You could do this by putting a trigger on your code table. Any time that someone added, deleted, or updated one of the rows in the table the trigger would be responsible for recreating the view with the correct statement.

OTHER TIPS

I was thinking, worse case, you could do something where the first row returned had all your column headers. Would be a bit tricky, and you'd probably have to suffer the performance hit for a UNION, but sounds doable.

You could write a program in Java or C or whatever that dynamically creates the "create view" statement using values from a database and then executes it.

If you're looking for a way to do it with only SQL statements, I agree that the answer is probably "can't be done" but I'm reluctant to make such statements as people are always coming up with clever ways to do something that I never thought of.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top