日期:2014-05-18  浏览次数:20322 次

!!!求教SQL语句...怎样将拼出的字符串型 字段名 可用于查询?
表Tab1内有字段及数据

Type P1 P2 P3
-------------------------------
1 0.15 0.5 1.3
2 0.14 0.8 1.2
3 0.13 0.6 1.5

要求用Sql语句根据Type内容查出所对应的价格

select   'P '+Convert(varchar(50),Type)   价格   from   tab1
              -----------------------------   这段是自己拼出的字符串
要求得到结果

价格
-----------
0.15
0.8
1.5

怎样将拼出的字符串型   字段名   可用于查询?

------解决方案--------------------
很多字段?还是很多数据?

------解决方案--------------------
up
------解决方案--------------------
declare @s varchar(1000)
set @s= 'select P '+ convert(varchar(50),type) + ' 价格 from tab1 '
exec(@s)
------解决方案--------------------
declare @s varchar(2000),@i int,@cnt
select @cnt=count(*) from tab1
set @i=1
set @s= ' '
while @i <@cnt
begin
select @s=@s+ 'select p '+cast(type as vachar)+ ' as 价格 from tab1 where type = '+cast(type as vachar)+ ' union all ' from tab1 where type=@i
set @i=@i+1
end
set @s=left(@s,len(@s)-10)
exec(@s)
------解决方案--------------------
如果Type不多的話,可以這麼寫

Select
Case Type When 1 Then P1
When 2 Then P2
When 3 Then P3
End As 价格
From
Tab1