2015-04-03 60 views
0

我從包含不明確列名的表中抽取數據(表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 
... 

This SO question comes close: Retrieve column names from a different table?

除了我必須鍵入/複製約200次每列。

有沒有辦法讓我加入他們來獲得名字?或者類似的東西?

回答

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 
+0

這太好了!我想我會在未來做到這一點。我最終做的是導出這兩個表並使用python來更改表。謝謝! – nfmcclure 2015-04-05 18:21:28

相關問題