Already review this question and it's not really what I'm looking for.
You see, I am generating a Sotred Procedure whose query becomes a sales report.
The condition is that, when it comes to specific dates, you must select from some tables and if it is another date then the FROM is from another table, so generate the query fragment in this way:
IF @fecha between '2017-01-01' and '2018-06-30'
BEGIN
SELECT id_tienda,sum(importe) as importe
into #vtaAA
FROM
(SELECT id_tienda, 0 as importe, 0 as unidades from #tdaZona
group by id_tienda
UNION
SELECT [IdTienda] as id_tienda,sum(ns) as importe, sum(qty) as unidades
FROM dbo.BaseVentasHistoria
where Fecha>=@fechaAnt and fecha < @fechaCAnt and idTienda in (select id_tienda from #tdaZona)
group by idtienda) as A
group by id_tienda
END
ELSE
BEGIN
SELECT id_tienda,sum(ventas) as ventas
into #vtaAA
FROM
(SELECT id_tienda collate Modern_Spanish_CI_AS as id_tienda, 0 as ventas from #tdaZona
group by id_tienda
UNION
select n_tickets.id_tienda,ISNULL(sum(importeeuros),0) as ventas
from dbo.baseVentasDiarias with(nolock)
inner join n_tickets on n_tickets.id_auto = baseVentasDiarias.id_auto
where Fecha>=@fechaAnt and fecha < @fechaCAnt and n_tickets.id_tienda in (select id_tienda collate Modern_Spanish_CI_AS as id_tienda from #tdaZona)
group by n_tickets.id_tienda) as A
group by id_tienda
END
The topic is this, that when I want to compile the SQL change it throws me these error messages
Mens 2714, Level 16, State 1, Procedure alertVta_Rockport, Line 92 There is already an object with the name '#vtaAA' in the database.
This is line 92: into #vtaAA FROM
Mens 156, Level 15, State 1, Procedure alertVta_Rockport, Line 100 Incorrect syntax near the keyword 'as'.
This is line 100: group by baseVentasDiarias.id_tienda) as A
Can anyone support me on why he marks this error? At first hand it occurs to me that it is because #vtaAA is in the IF and in the ELSE, but that should not be a problem because it is only being created once according to the date received. Or am I wrong?