sql - Rename columns in 1 table to row values in another table -
ok, have 2 tables in all:
table 1has these 3 columns not meaningfulvarcharvalue:q19243 q19244 q19245table 2has 2 columnscolumnname,textvalue.
columnname holds values of name of 3 columns in table 1 (q19243 etc) , has corresponding column called textvalue holds friendly description of q19243 means.
so there 3 records in table 2, 1 each column in table 1.
i rename these 3 columns in table 1 equal whatever in textvalue column in table 2. dynamically rather simple update statement rename columns. sorry did not attach screen shots not see attach button so...
if run code create example of 2 tables should have better idea of i'm referring to.
create table #table1 (q19243 varchar(10),q19244 varchar(10),q19245 varchar(10)) create table #table2 (columnname varchar(10),textvalue varchar(50)) insert #table2 select 'q19243','provider name' insert #table2 select 'q19244','the provider see' insert #table2 select 'q19245','how long going provider' select * #table1 select * #table2 drop table #table1 drop table #table2
since purpose of column rename output purposes only, can use query against table2 create dynamic sql specific table1 aliases column names on select.
(the following example uses sample code in original question , differs between --============== lines)
create table #table1 (q19243 varchar(10),q19244 varchar(10),q19245 varchar(10)) create table #table2 (columnname nvarchar(10),textvalue nvarchar(50)) insert #table2 select 'q19243','provider name' insert #table2 select 'q19244','the provider see' insert #table2 select 'q19245','how long going provider' select * #table1 select * #table2 --========================================= declare @sql nvarchar(max) select @sql = coalesce(@sql + n',', n'select') + n' t1.' + t2.columnname + n' [' + t2.textvalue + n']' #table2 t2 set @sql = @sql + n' #table1 t1' select @sql exec(@sql) --========================================= drop table #table1 drop table #table2 the value of @sql after select @sql= query is:
select t1.q19243 [provider name], t1.q19244 [the provider see], t1.q19245 [how long going provider] #table1 t1
note: need square-brackets around field name alias (value table2.textvalue) there spaces in string.
Comments
Post a Comment