Ok, so I have 2 tables in all:
Table 1
has these 3 columns which are not meaningful as they are just avarchar
value:Q19243 Q19244 Q19245
Table 2
has 2 columnsColumnName
andTextValue
.
ColumnName
holds the values of the name of the 3 columns in Table 1
(Q19243
etc) and also has a corresponding column called TextValue
which holds a friendly description of what Q19243
actually means.
So there are 3 records in Table 2
, 1 for each column in Table 1
.
I would like to rename these 3 columns in Table 1
to equal whatever is in the TextValue
column in Table 2
. I would like to do this dynamically rather than a simple UPDATE
statement to rename the columns. Sorry I did not attach screen shots but I do not see an attach button to do so...
If you run this code to create an example of the 2 tables then you should probably have a better idea of what 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 into #Table2 select 'Q19243','Provider Name'
Insert into #Table2 select 'Q19244','The Provider You Usually See'
Insert into #Table2 select 'Q19245','How Long Going to Provider'
select * from #Table1
select * from #Table2
drop table #Table1
drop table #Table2
Since the purpose of the column rename is for output purposes only, you can use a query against Table2 to create Dynamic SQL specific to Table1 that aliases the column names on the SELECT.
(the following example uses the sample code in the original question and only differs by what is between the
--==============
lines)The value of
@SQL
after theSELECT @SQL=
query is:Note: you need the square-brackets around the field name alias (value from Table2.TextValue) as there are spaces in the string.