读书人

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

发布时间: 2012-01-15 22:57:48 作者: rapoo

请教一个显示变量值问题!
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
*/

读书人网 >SQL Server

热点推荐