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

语句报错,求解!!
fyear fperiod fcustomer mount
2012 2 2342 74933.8000000000
2012 2 2344 1526.6200000000
2012 3 2344 16047.4000000000
2012 2 2346 7156.1900000000
2012 3 2346 11765.2300000000
2012 1 2348 3344.0000000000
2012 2 2348 10530.0000000000
2012 1 2353 2855.5800000000
2012 2 2353 3381.8400000000
2012 3 2353 4862.3100000000
2012 2 2357 .5000000000
2012 3 4181 180.0000000000


想把fperiod转成横式
fyear fcustomer 1 2 3 4 5
.....................................


declare @sql varchar(8000)
set @sql = 'select fcustomer '
select @sql = @sql + ' , max(case fperiod when ''' + fperiod + ''' then fremainamount else 0 end) [' + fperiod + ']'
from (select distinct fperiod from yin5) as a
set @sql = @sql + ' , sum(fremainamount) 总分 from yin5 group by fcustomer '
exec(@sql)  

语法正确,执行时报错,求解。。。
将 varchar 值 '' then fremainamount else 0 end) [' 转换为数据类型为 int 的列时发生语法错误。




------解决方案--------------------
SQL code
declare @sql varchar(8000)
set @sql = 'select fcustomer '
select @sql = @sql + ' , max(case fperiod when ''' + ltrim(fperiod) + ''' then fremainamount else 0 end) [' + ltrim(fperiod) + ']'
from (select distinct fperiod from yin5) as a
set @sql = @sql + ' , sum(fremainamount) 总分 from yin5 group by fcustomer '
exec(@sql)

------解决方案--------------------
整型数值不能直接与字符串相加,需要把整型转为字符型,ltrim()函数是一个去除字符串左空格函数,利用它也可以把整型转为字符型
------解决方案--------------------
树哥正解,昨天我也遇到的!
------解决方案--------------------

declare @sql varchar(8000)
set @sql = 'select fcustomer '
select @sql = @sql + ' , max(case fperiod when ''' + fperiod + ''' then fremainamount else ''0'' end) [' + fperiod + ']'
from (select distinct fperiod from yin5) as a
set @sql = @sql + ' , sum(fremainamount) 总分 from yin5 group by fcustomer '
exec(@sql)