I have a issue with a query in SQL SERVER, I have wrote this Dynamic Query:
declare @cont int
declare @sqlquery varchar(1000)
declare @sqlquery2 varchar(500)
declare @sqlquery3 varchar(2000)
declare @anho varchar(4)
set nocount on
drop table ti
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'
exec(@sqlquery3)
set nocount off
select * from ti
Well, the issue that i have is when I execute the query with a Store Procedure, It's Work's well, but when I execute only the code, SQL SERVER show me a error message like this:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'a'.
The query is work's ok, but i want to hide the error message, can anybody help me to this issue?
exec (@sqlquery2)because,@sqlquery2has(a.[.... You're trying to assign the value of the query into an variable with EXEC, you should do this another way.@sqlqueryand@sqlquery2before executing them and post the query here?