pivot - sql server - getting values from one table with columns' names stored in another table -
i have several tables. these simplified versions of tables:
userstable: userid firstname lastname middleinit suffix age position 1 john graham p. jr. 35 analyst ii 2 bill allen t. iii 45 programmer 3 jenny smith k. 25 systems engineer 4 gina todd j. 55 analyst ii tabletypes: tabletypeid tabletype 1 names 2 positions 3 age
tabletypeid primary key in tabletypes , foreign key in tablefields.
tablefields: fieldid tabletypeid fieldname description 1 1 firstname descr1 2 1 lastname descr2 3 1 middleinit descr3 4 1 suffix descr4
fieldid primary key in tablefields , foreign key in modifieduserstable.
i need fill modifieduserstable values userstable looks this:
modifieduserstable: id userid fieldid value 1 1 1 john 2 1 2 graham 3 1 3 p. 4 1 4 jr. 5 2 1 bill
etc.
i need columns userstable listed in fieldname column in tablefields table. don't know number of rows (fieldnames) or names in advance in tablefields. thought should try use pivot. can comma separated string of column names , dynamically convert them columns.
doesn't seem give me need. how fill modifieduserstable? suggestions? thanks!
ddl data
create table userstable( userid int, firstname varchar(100), lastname varchar(100), middleinit varchar(100), suffix varchar(100), age int, position varchar(100)); insert userstable select '1','john','graham','p.','jr.','35','analyst ii' union select '2','bill','allen','t.','iii','45','programmer i' union select '3','jenny','smith','k.',null,'25','systems engineer' union select '4','gina','todd','j.',null,'55','analyst ii'; create table tabletypes( tabletypeid int, tabletype varchar(100)); insert tabletypes select 1, 'names' union select 2, 'positions' union select 3, 'age'; create table tablefields( fieldid int,tabletypeid int,fieldname varchar(100),description varchar(100)); insert tablefields select '1','1','firstname','descr1' union select '2','1','lastname','descr2' union select '3','1','middleinit','descr3' union select '4','1','suffix','descr4'; create table modifieduserstable( id int identity, userid int, fieldid int, value varchar(max));
the script populate modifieduserstable
declare @sql nvarchar(max) select @sql = coalesce(@sql+ ' union ', '') + ' select userid,' + right(fieldid,12) + ',' + quotename(fieldname) + ' userstable' tablefields set @sql = @sql + ' order userid, 2' -- print @sql -- uncomment see generated sql exec (@sql)
Comments
Post a Comment