I have a table, which links to another table specifying the the value of a key-value pair. The Value table then links to a table holding the name (key). The tables are defined (near enough) as follows:
---------------
Entity
---------------
EntityID
Name
Some other data
---------------
Value
----------------
ValueID
EntityID
Value
---------------
Key
---------------
KeyID
ValueID
Name
Each Entity can have many Values and each Value has one Key. Each Entity may not have the same number of Values. Basically, this structure is allowing me to add table rows dynamically, without modifying the Entity table.
I want to do a select * on the Entity table, using the Key.Name field as a column header, and displaying the appropriate Value.Values
Is there a dynamic structure available in SQL that I can do an insert into for each row in Entity, then return a select on?
I hope this makes sense!
Based on your description, it sounds like you want to
PIVOTthe data. There are two ways to do this with PIVOT, either a Static Pivot where you code the columns to transform or a Dynamic Pivot which determines the columns at execution.Static Pivot:
See SQL Fiddle With Demo
A Dynamic Pivot determined the columns at run-time:
See SQL Fiddle With Demo
Both of these can be placed in a stored procedure. If you post some sample data for each of your tables and then the desired result, it would be easier to determine the proper query.