请教一个显示变量值问题!
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_name Varchar(10),
m1 Int,
m2 Int,
m3 Int)
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_name monthly m_value
pc1 1 3
pc2 1 6
pc1 2 5
pc2 2 9
pc1 3 8
pc2 3 12
*/