假设存储数据的表City有三列,分别是CityName,Population,Area,存有三条数据:
北京 1961 16410.5
上海 2302 6340.5
广州 1018 3843.4另一个表Appendix存储表City中列的属性,包括RowName,ChineseName,Unit三列,数据内容为
CityName 城市 null
Population 人口 万人
Area 面积 平方公里
现在想把查询结果显示成如下形式:
城市 人口(万人) 面积(平方公里)
北京 1961 16410.5
上海 2302 6340.5
广州 1018 3843.4
请问应如何实现?请教在数据行列数都不确定时的通用方法
还是只能用程序语言读取后自己设置显示?
北京 1961 16410.5
上海 2302 6340.5
广州 1018 3843.4另一个表Appendix存储表City中列的属性,包括RowName,ChineseName,Unit三列,数据内容为
CityName 城市 null
Population 人口 万人
Area 面积 平方公里
现在想把查询结果显示成如下形式:
城市 人口(万人) 面积(平方公里)
北京 1961 16410.5
上海 2302 6340.5
广州 1018 3843.4
请问应如何实现?请教在数据行列数都不确定时的通用方法
还是只能用程序语言读取后自己设置显示?
如果知道要从city中查什么,可以用动态语句:
create table City(CityName nvarchar(10),Population int,Area decimal(10,1))
insert into City select '北京',1961, 16410.5
insert into City select '上海',2302, 6340.5
insert into City select '广州',1018, 3843.4
create table Appendix(RowName varchar(20),ChineseName nvarchar(10),Unit nvarchar(10))
insert into Appendix select 'CityName','城市',null
insert into Appendix select 'Population','人口','万人'
insert into Appendix select 'Area','面积','平方公里'
go
declare @sql nvarchar(max)
select @sql='select
cityname as ['+(select top 1 ChineseName +isnull('('+unit+')','') from appendix where rowname='cityname')+'],
Population as ['+(select top 1 ChineseName +isnull('('+unit+')','') from appendix where rowname='Population')+'],
Area as ['+(select top 1 ChineseName +isnull('('+unit+')','') from appendix where rowname='Area')+']
from city'
exec(@sql)
/*
城市 人口(万人) 面积(平方公里)
---------- ----------- ---------------------------------------
北京 1961 16410.5
上海 2302 6340.5
广州 1018 3843.4(3 行受影响)*/
go
drop table city,appendix
go
--> -->
if not object_id(N'City') is null
drop table City
Go
Create table City([CityName] nvarchar(2),[Population] int,[Area] decimal(18,1))
Insert City
select N'北京',1961,16410.5 union all
select N'上海',2302,6340.5 union all
select N'广州',1018,3843.4
Go
use Tempdb
go
--> -->
if not object_id(N'Appendix') is null
drop table Appendix
Go
Create table Appendix([RowName] nvarchar(10),[ChineseName] nvarchar(2),[Unit] nvarchar(4))
Insert Appendix
select N'CityName',N'城市',null union all
select N'Population',N'人口',N'万人' union all
select N'Area',N'面积',N'平方公里'
GoDECLARE @s NVARCHAR(4000)
Select @s=ISNULL(@s+',',' select ')+QUOTENAME([RowName])+' as ['+[ChineseName]+ISNULL('('+[Unit]+')','')+']' from Appendix
exec (@s+' from City')
/*
城市 人口(万人) 面积(平方公里)
北京 1961 16410.5
上海 2302 6340.5
广州 1018 3843.4
*/