Change Columns Name dynamically in sql

前端 未结 3 957
面向向阳花
面向向阳花 2021-01-26 12:16

I have a query result like this :

Date       User1 User2 User3 ....
----------------------------------
1/1/2000   55     78    98   ...
1/1/2001   26     33    5         


        
3条回答
  •  抹茶落季
    2021-01-26 12:46

    To get the mapping You can use a lookup table of old column name to new column name for example

    CREATE TABLE colname(
      oldname varchar(20),
      newname varchar(20)
    )
    
    insert into colname values ( 'user1','user1 (blue)');
    insert into colname values ( 'user2','user2 (green)');
    

    then you can build an sql statement that uses this mapping

    declare @sq varchar(2000)
    set @sq ='select date'
    select @sq = @sq +  ',' + oldname + ' as [' + newname +']' from colname
    set @sq = @sq + 'from ( existing query goes here ) ' 
    select @sq
    

    when the sql in @sq looks good you can replace the last select with

    exec ( @sq ) 
    

    to run the query

提交回复
热议问题