Hi,
We had someone that was big on "object oriented" table design where there is an "X" table that basically lets you dynamically add columns to a table. So you have a table like this:
FOREIGN_KEY
FIELD_NAME
FIELD_VALUE
You then do endless left joins against the same table to get all the FIELD_NAMEs to show up as columns in your query.
I'm facing a situation now where I don't necessarily know what all the valid FIELD_NAMEs are, however, so I'm trying to create a stored procedure that selects all the distinct FIELD_NAMEs then creates a dynamic SQL statement to join them all together for me so that the resulting query's table has one column for each valid FIELD_NAME.
Unfortunately, I'm a newbie at tsql and although I know how to get the distinct FIELD_NAMEs into a variable table and I know you can use EXEC to execute dynamic SQL within an SP, I don't know how to build the SQL statement in tsql. I think it will involve some sort of loop, but does anyone have any pointers on how I should go about this?
Thanks!
P.S. I'm using SQL 2005
We had someone that was big on "object oriented" table design where there is an "X" table that basically lets you dynamically add columns to a table. So you have a table like this:
FOREIGN_KEY
FIELD_NAME
FIELD_VALUE
You then do endless left joins against the same table to get all the FIELD_NAMEs to show up as columns in your query.
I'm facing a situation now where I don't necessarily know what all the valid FIELD_NAMEs are, however, so I'm trying to create a stored procedure that selects all the distinct FIELD_NAMEs then creates a dynamic SQL statement to join them all together for me so that the resulting query's table has one column for each valid FIELD_NAME.
Unfortunately, I'm a newbie at tsql and although I know how to get the distinct FIELD_NAMEs into a variable table and I know you can use EXEC to execute dynamic SQL within an SP, I don't know how to build the SQL statement in tsql. I think it will involve some sort of loop, but does anyone have any pointers on how I should go about this?
Thanks!
P.S. I'm using SQL 2005