如何从另一个表动态化列别名

时间:2016-01-15 11:10:48

标签: sql sql-server tsql

我有下面的查询,我正在寻找从另一个表中动态列名称标签。 在表#Tmp2中,Dim1根据Dim1.Num而变化,例如我可以拥有 对于Dim1.Num = 1 => Dim1 =BusinessUnit
在其他cas我可以有Dim1.Num = 1 => Dim1 =Department

SELECT Dim1.Dim1 ,Dim1.ValueDim1  ,
       Dim2.Dim2 ,Dim2.ValueDim2  ,
       #Tmp1.Amount

INTO   #Tmp3

FROM   #Tmp1

INNER JOIN #Tmp2 as Dim1 on Dim1.id = #Tmp1.id And Dim1.Num=1
INNER JOIN #Tmp2 as Dim2 on Dim1.id = #Tmp1.id And Dim2.Num=2

结果如下:

Dim1            ValueDim1  Dim2         ValueDim2  Amount
BusinessUnit    002        Department   027        1000

但我想要这个结果

BusinessUnit    ValueDim1  Department   ValueDim2  Amount
BusinessUnit    002        Department   027        1000

也就是说,根据#Tmp2.Num的值,可以更改列的适用名称。

mybe像这样的事情

SELECT Dim1.Dim1 AS (select Dim from #Tmp2 where #Tmp2.Num = 1)

1 个答案:

答案 0 :(得分:2)

您可以使用动态SQL:

DECLARE @ColName VARCHAR(20) = (select Dim from #Tmp2 where #Tmp2.Num = 1)

EXEC('SELECT Dim1.Dim1 ['+@ColName+'] ,Dim1.ValueDim1  ,
       Dim2.Dim2 ,Dim2.ValueDim2  ,
       #Tmp1.Amount

INTO   #Tmp3

FROM   #Tmp1

INNER JOIN #Tmp2 as Dim1 on Dim1.id = #Tmp1.id And Dim1.Num=1
INNER JOIN #Tmp2 as Dim2 on Dim1.id = #Tmp1.id And Dim2.Num=2')

此限制(以及您的一般问题)是,如果您的#Tmp2有两条记录具有相同的Num,则查询将抛出Subquery returned more than one value错误。解决这个问题的唯一方法是更改​​@ColName查询,使其只返回一个值:

DECLARE @ColName VARCHAR(20) = (select TOP 1 Dim from #Tmp2 where #Tmp2.Num = 1)

<强>更新

如果获取列名的查询可能返回0条记录,则按如下方式修改查询:

DECLARE @ColName VARCHAR(20) = (
    select Dim from #Tmp2 where #Tmp2.Num = 1 
    UNION 
    SELECT 'DefaultValue' WHERE NOT EXISTS (select Dim from #Tmp2 where #Tmp2.Num = 1)
    )

但是,如果您的查询返回一条记录,但您要用作列名的列中的值为null,则修改查询,如下所示:

DECLARE @ColName VARCHAR(20) = (select ISNULL(Dim,'DefaultValue') from #Tmp2 where #Tmp2.Num = 1)