通过将表列映射到其他表的列值来重命名表列

时间:2019-07-30 09:26:41

标签: sql sql-server database

我有2张桌子:

表A:

Perspectiveid   ColumnOrder   UIDisplayName 
-------------------------------------------
   213              1           Alpha
   213              2           Beta
   213              3           Gamma

表B:第Id, Col1, Col2, Col3

我希望表B中的最终结果为:

(`Id, Alpha, Beta, Gamma`)

Col1中的table B对应于ColumnOrder 1中的table A,应重命名为UIDisplayName[Alpha]的{​​{1}}

2 个答案:

答案 0 :(得分:1)

您可以使用数据透视将行转换为列。您可以使用此链接以获取有关枢轴link的更多信息
对于您的查询:-

 ; with cte as (
 select Perspectiveid,cast(ColumnOrder as varchar(max)) as ColumnOrder,UIDisplayName from tableA)
 select * into temptable from (
 select Perspectiveid,ColumnOrder,UIDisplayName from cte
 ) as d
 pivot (
 max(ColumnOrder) for UIDisplayName in ( [Alpha], [Beta], [Gamma] )
 ) as P

这将为您提供

将此设置为临时表

   Perspectiveid   | [Alpha] | [Beta]  | [Gamma]
       213             1          2        3

temptable删除

   delete from temptable

现在将数据从yourtable插入到该temptable的方式为

  insert into temptable ( Perspectiveid , [Alpha], [beta], [gamma] )
  select id, col1, col2, col3 from #tableb  

在那之后放下tableB,然后将您的临时表重命名为tableB

  Drop table #tableB

  GO
  select * into #tableB from temptable


  GO

  Drop table temptable

OR

如果您想单独更改每一列,请尝试

 select ' exec sp_rename ''tableb.col' + cast(columnorder as varchar(5)) + ''', ''' + UIDisplayName + ''', ''COLUMN'''  from tableA

这将为您提供查询以分别执行和更改列名称。

答案 1 :(得分:0)

您可以使用CURSOR执行动态sp_rename

DECLARE @ColumnOrder AS INTEGER
DECLARE @UIDisplayName AS VARCHAR(32)

DECLARE C_ColumnTitle CURSOR FOR
    SELECT Table_A.ColumnOrder,
        Table_A.UIDisplayName
    FROM Table_A

OPEN C_ColumnTitle
FETCH NEXT FROM C_ColumnTitle INTO @ColumnOrder, @UIDisplayName

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE @SQLString AS VARCHAR(MAX)
    SELECT @SQLString = 'EXECUTE sp_rename ''Table_B.Col' + CAST(@ColumnOrder AS VARCHAR(32)) + ''', ''' + @UIDisplayName + ''', ''COLUMN'';'

    EXEC(@SQLString)

    FETCH NEXT FROM C_ColumnTitle INTO @ColumnOrder, @UIDisplayName

END

CLOSE C_ColumnTitle
DEALLOCATE C_ColumnTitle