Código SQL:
Ver originalDECLARE @cont INT
DECLARE @sqlquery VARCHAR(1000)
DECLARE @sqlquery2 VARCHAR(500)
DECLARE @sqlquery3 VARCHAR(2000)
DECLARE @anho VARCHAR(4)
SET nocount ON
SET @anho = (SELECT YEAR(getdate()))
SET @cont = 1
SET @sqlquery = ''
while @cont <= 12
BEGIN
SET @sqlquery2 = '(a.['+@anho + RIGHT('00'+CAST(@cont AS VARCHAR),2)+']+b.['+@anho + RIGHT('00'+CAST(@cont AS VARCHAR),2)+']+c.['+@anho + RIGHT('00'+CAST(@cont AS VARCHAR),2)+']+d.['+@anho + RIGHT('00'+CAST(@cont AS VARCHAR),2)+']) as ['+@anho + RIGHT('00'+CAST(@cont AS VARCHAR),2)+'],'
--exec (@sqlquery2)
SET @sqlquery = @sqlquery + @sqlquery2
--exec (@sqlquery)
SET @Cont = @Cont + 1
END
--exec(@sqlquery)
SET @sqlquery3 = 'select a.gestion,'+@sqlquery+' '+quotename('GES08','''')+' as COD_GES into ti from Llamadas_Mensual_Oro_Final a inner join Llamadas_Mensual_plata_Final b on a.gestion = b.gestion inner join Llamadas_Mensual_Reten_Final c on b.gestion = c.gestion inner join Llamadas_Mensual_cable_Final d on c.gestion = d.gestion'
EXECUTE sp_executesql(@sqlquery3)
con eso obtienes lo que necesitas, pregunta para que es la tabla "ti"?