给出2个临时表:
A B
a1 b1
A B C
a2 b2 c2
然后,通过简单地将A,B和C列分别重命名为COL1,COL2和COL3,我创建了#tmp3(来自#tmp)和#tmp4(以及#tmp2)。
我目前有:
Create table #tmp5 (
A varchar (100)
, B varchar (100
, C varchar (100)
)
Declare @column1 as varchar(256)
Declare @column2 as varchar(256)
Declare @column3 as varchar(256)
Select @column1 = column_name
from tempdb.INFORMATION_SCHEMA.columns
where TABLE_NAME = #tmp2 and ORDINAL_POSITION = 1
Select @column2 = column_name
from tempdb.INFORMATION_SCHEMA.columns
where TABLE_NAME = #tmp2 and ORDINAL_POSITION = 2
Select @column3 = column_name
from tempdb.INFORMATION_SCHEMA.columns
where TABLE_NAME = #tmp2 and ORDINAL_POSITION = 3
Insert into #tmp5
Select
(Case when @column1 = 'A' then COL1
when @column2 = 'A' then COL2
when @column3 = 'A' then COL3 else NULL end) as A
(Case when @column1 = 'B' then COL1
when @column2 = 'B' then COL2
when @column3 = 'B' then COL3 else NULL end) as B
(Case when @column1 = 'C' then COL1
when @column2 = 'C' then COL2
when @column3 = 'C' then COL3 else NULL end) as C
from #tmp4
我想运行以上查询,以便它对两种输入类型均有效(#tmp 2列和#tmp2 3列)。当前,该代码仅适用于3列表,因为我收到一条错误消息,指出COL3无效。我将如何更改以适应两种类型?
我尝试使用if语句,当when语句尝试这种情况,但似乎没有在查询中使用COL3的情况... :(