Syntax error converting the varchar value '' 'to a column of data type int
declare @sql1 nvarchar(4000)
set @sql1 = 'select a.[owner] '
select @sql1 = @sql1 + ' , sum(case a.week when ''' + week + ''' then a.productivity_target else 0 end)[' + week + '],sum(case a.week when ''' + week + ''' then a.productivity_contribution else 0 end) [' + week + ']'
from (select distinct week from pfad_productivity a) as t
set @sql1 = @sql1 + ' from pfad_productivity agroup by a.[owner] '
exec(@sql1)
此上是一個存儲過程,其中week字段是整型。
在執行時出錯為:Syntax error converting the varchar value '' then a.productivity_target else 0 end)['to a column of data type int
但是將week字符轉換為字符型,就不會出錯。但是我必須要week為整型,請問我該怎麼解決,謝謝。
------解决方案--------------------
SQL code
declare @sql1 nvarchar(4000)
set @sql1 = 'select a.[owner] '
select @sql1 = @sql1 + ' , sum(case a.week when ''' +ltrim(week)+ ''' then a.productivity_target else 0 end)[' + ltrim(week)+ '],sum(case a.week when ''' + ltrim(week)+ ''' then a.productivity_contribution else 0 end) [' + ltrim(week)+ ']'
from (select distinct week from pfad_productivity a) as t
set @sql1 = @sql1 + ' from pfad_productivity agroup by a.[owner] '
exec(@sql1)