如何在查询一个表示,将这个表的列名替换成另一个表的指定字段的值?

img


如图,表A的列名是英文的,表B中有英文字段名的对应中文解释,想在查询A表时,列名用表B中的中文替换显示出来,就像查询结果中显示的那样,应该怎么做?怎么做到动态替换,不是一个列名一个列名的 AS 这种方式,因为不确定会有多少列

这种应该实现不了,建立不了关联。而且你只是想替换显示的列名而不是值。

根据不同的数据库环境,有不同的写法

这个是mssql的,可以参考下


create table tb_a(id int identity primary key,name nvarchar(10),age int,height int,weight int,sex nvarchar(2))
create table tb_b(id int identity primary key,field_name varchar(20),field_txt nvarchar(20))

insert into tb_a(name,age,height,weight,sex) values('aaa',18,165,102,'女'),('bbb',22,174,142,'男'),('张三',20,170,120,'男')

insert into tb_b(field_name,field_txt) values('name','姓名'),('age','年龄'),('height','身高'),('weight','体重'),('sex','性别')

declare @sql nvarchar(max)

set @sql = 'select ' + stuff((
    select ',' + c.name + ' as ' + ISNULL(b.field_txt,c.name)
    from syscolumns c 
    left join tb_b b on c.name=b.field_name
    where c.id=OBJECT_ID('tb_a')
    order by colorder
    for xml path('')
),1,1,'') + ' from tb_a'

select * from tb_a a

select * from tb_b

exec(@sql)

drop table tb_b
drop table tb_a


img