首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请问一个显示变量值有关问题

2012-01-15 
请教一个显示变量值问题!set@sql selectP_name, +@lw_name+asmonthly, +@lw_name+asm_valuefromt_errect@

请教一个显示变量值问题!
set   @sql= 'select   P_name, '+@lw_name+ '   as   monthly, '+@lw_name+ '   as   m_value   from   t_errect '
@lw_name为表中字段名称,请问在执行exec(@sql)时,如何将第一个出现的@lw_name对应的字段名称显示在查询中而不是字段对应的值?

[解决办法]
Create Table t_errect
(P_nameVarchar(10),
m1Int,
m2Int,
m3Int)
Insert t_errect Select 'pc1 ', 3, 5, 8
Union All Select 'pc2 ', 6, 9, 12
GO
declare @m_str varchar(50),@monthly int,@sql varchar(2000)
select @monthly=1, @sql = ' '
while (@monthly <4)
begin
set @m_str= 'm '+cast(@monthly as varchar(5))
set @sql= @sql + ' union all select P_name, ' ' '+Rtrim(@monthly)+ ' ' ' as monthly, '+@m_str+ ' as m_value from t_errect '
set @monthly=@monthly+1
end
select @sql = Stuff(@sql, 1, 10, ' ')
exec(@sql)
GO
--Result
/*
P_namemonthlym_value
pc113
pc216
pc125
pc229
pc138
pc2312
*/

热点排行