我从带有不明确的列名的表中提取数据(表1)。还有另一个表格,其中包含模糊列名称含义的字典(表2)。数据集中有足够的列,我不想输入'SELECT a AS a_name,b AS b_name ...'。我想从表1中获取所有数据,但是根据表2重命名列。
示例表1:
id A1 A2 A3 B1 B2 B3
1 foo1 foo2 foo3 1 1 0
2 bar1 bar2 bar3 2 3 4
...
示例表2:
column_ref col_definition
A1 apples
A2 aardvarks
A3 androids
B1 bears
B2 beers
B3 boats
示例输出:
id apples aardvarks androids bears beers boats
1 foo1 foo2 foo3 1 1 0
2 bar1 bar2 bar3 2 3 4
...
这个问题很接近: Retrieve column names from a different table?
除了我必须每列输入/复制约200次。
我有没有办法加入他们的名字?或类似的东西?
答案 0 :(得分:1)
这几乎可以做你想要的,除非它不保留数据类型。我使用了nvarchar。
/* Create new table for data with new column headers */
create table Table_3
(
/* Temp column, will delete later */
T3 varchar
)
/* Select column definitions into temp table */
select *
into #TempTable
from
(
select a.col_definition from Table_2 a
join
(
/* Get column names for Table_1 to join on */
select column_name from SANDBOX.INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME = N'Table_1'
) b
on a.column_ref=b.column_name
) T
declare @ColDf nvarchar(max)
declare @sql nvarchar(max)
/* Loop through column definitions in #TempTable */
while exists (select * from #TempTable)
begin
select @ColDf = (select top 1 ColDf
from #TempTable
order by ColDf asc)
/* Add column using each column definition as column name */
set @sql = 'alter table Table_3 add ' + @ColDf + ' nvarchar(max)'
exec (@sql)
delete #TempTable
where ColDf = @ColDf
end
/* Remove temp table */
drop table #TempTable
/* Remove temp column */
alter table Table_3
drop column T3
/* Copy data from Table_1 into Table_3 */
insert into Table_3
select * from Table_1
/* View results */
select * from Table_3