How can I prefix all column names in a T-SQL function?

后端 未结 2 1047
日久生厌
日久生厌 2020-12-22 06:16

I have a table T with 2 columns C1 and C2

I want a function that returns T but after prefixing all column names with \"PREFIX_\".

The prefix is a dynamic str

相关标签:
2条回答
  • 2020-12-22 07:02

    This will do it even when you don't know the columns already.

    declare @prefix varchar(20)
    declare @sqltext nvarchar(500)
    set @prefix = 'prefix_'
    
    declare @columnnames varchar(500)
    
    select @columnnames = coalesce(@columnnames, '')+',' +column_name + ' '+ @prefix+column_name 
    from INFORMATION_SCHEMA.COLUMNS a where table_name = 't' and table_schema = 'dbo'
    
    set @sqltext = 'select '+stuff(@columnnames,1,1,char(0))+' from t'
    
    exec(@sqltext)
    
    0 讨论(0)
  • 2020-12-22 07:09

    As its for a known number of columns you can construct the SQL string with the alias and exec() it;

    declare @prefix varchar(32) = 'prefix_'
    declare @sql    nvarchar(1024) 
    
    set @sql = 'select C1 as [' + @prefix + 'C1], C2 as [' + @prefix + 'C2] from T'
    exec(@sql)
    
    0 讨论(0)
提交回复
热议问题