
/****** Object:  StoredProcedure [dbo].[Get_Submayor]    Script Date: 05/02/2016 11:42:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER  PROCEDURE Get_Submayor 
                 @Cod_Desde varchar(20), 
                 @Cod_Hasta varchar(20),
                 @List_alma varchar(8000),
                 @List_secc varchar(8000), 
				 @FDesde datetime, 
				 @FHasta datetime, 
				 @Id_TMov int,
				 @IdTerminal int
AS

BEGIN
/*  Modificado por: Luis Abarca Mora
	Fecha: 28 Enero 2014
	Detalle: El procedimiento para extraer la informacion de
		submayor de inventario, es demasiado lento, 
		dado que toma toda la informacion de operaciones, 
		desde el momento de la instalacion, hasta el dia del reporte
		y solo hasta el final, filtra los datos correspondientes
		a la fecha suministrada.
		
		Se creo la tabla [temporal], donde se filtra la informacion
		correspondiente a las fechas suministradas, con esto los calculos
		a realizar se reducen solo a la informacion entre esas fecha,
		y no como anteriormente donde tomaba toda la informacion, desde 
		el momento de la instalacion.
		
		*Se elimino la intrucción Existe_TablaSaldo, en Nacazcol el 
		Servidor no reconoce esa instrucción
				
*/


DECLARE @Cad varchar(8000),
        @Filtro_Articulo varchar(200),
        @Filtro_Destino  varchar(8000),
        @Id_Cmov int,
        @FechaSaldo datetime

----------------------------------------------------------
/* 01 Se resta [1] a la fecha para obtener la fecha anterior
   a la fecha suministrada
*/
----------------------------------------------------------
Set @FechaSaldo = @FDesde - 1

If @Id_TMov is not null 
  Select @id_cmov = id_cmov 
          From stoktmov Where id_tmov = @id_tmov

-----------------------------------
/* 02 Creo tabla temporal */
-----------------------------------

Declare @TablaTemp Table (id_smay int,id_operacion int,
                          id_arti int,consecutivo_act int,
                          id_alma smallint,id_secc smallint NULL,
                          fec_oper datetime,id_dmov smallint,
                          unico uniqueidentifier)

CREATE TABLE #Temporal
             (id_smay int,id_operacion int,
              id_arti int,consecutivo_act int,
              id_alma smallint,id_secc smallint NULL,
              fec_oper datetime,id_dmov smallint,
              unico uniqueidentifier) 
	
Create Table #SubMayor 
			(id_alma int,id_secc int,id_arti int, 
			cod_arti varchar(20),desc_arti varchar(40),
			cantidad numeric(20,4),importe numeric(20,4),
			costo numeric(20,4),id_dmov int,
			fec_oper datetime,consecutivo int,
			consecutivo_act int,referencia char(10),
			id_oper int,fec_ent datetime,
			orden int,observaciones varchar(5000),
			id_unme int,cant_um numeric(20,4),
			vCant numeric(20,4),IdSmay int)

Create TABLE #TempSaldos
               ([Id_arti] [int] NULL,
	             [Id_Alma] [int] NULL,
	             [Id_Secc] [int] NULL,
	             [Cantidad] [numeric](20, 4) NULL,
	             [Importe] [numeric](20, 4) NULL)

--------------------------------------------------
/*  03 Agregado 01
	Inserta la informacion en la tabla temporal 
	de acuerdo con la fecha ingresa,
	esto es para reducir el tiempo de la generacion 
	del reporte 
	*/
--------------------------------------------------	
Insert Into #Temporal 
       Select * from STOKSMAY
                where fec_oper between @FDesde
                and @FHasta

Insert Into @TablaTemp
		Select * from #Temporal 

--------------------------------------------------		
/* 04 Preparo los parámetros */
--------------------------------------------------   
   Select @Filtro_articulo = ''
   If @cod_desde is not NULL and @cod_hasta is not NULL
      Select @Filtro_articulo = ' AND arti.FullArtiCode between ' 
             + CHAR(39) + @cod_desde + CHAR(39) 
             + ' and ' + CHAR(39) + @cod_hasta + CHAR(39)
   Else
      Begin 
         If @cod_desde is not NULL
            Select @Filtro_articulo = ' AND arti.FullArtiCode >= ' 
                                      + CHAR(39) + @cod_desde + CHAR(39)
         Else
	   If @cod_hasta is not NULL
	      Select @Filtro_articulo = ' AND arti.FullArtiCode <= ' 
	                                + CHAR(39)+ @cod_hasta + char(39)
      End

   Select @filtro_destino = ''
   If @list_alma is not NULL and @list_secc is not NULL
      Select @filtro_destino = ' AND (smay.id_alma in (' + @list_alma + ') 
                                or smay.id_secc in (' + @list_secc + ')) '
   Else
      Begin 
         If @list_alma is not NULL
            Select @filtro_destino = ' AND smay.id_alma in (' + @list_alma + ') '
         Else
	If @list_secc is not NULL
	   Select @filtro_destino = ' AND smay.id_secc in (' + @list_secc + ') '
      End

--------------------------------------------------
/* 05 Inicio obtener [Inventario Inicial] */   
--------------------------------------------------

   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 0)
   Begin
      Select @Cad = 'INSERT #SUBMAYOR
		SELECT smay.id_alma, smay.id_secc, smay.id_arti,
			    cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
				cantidad=convert(numeric(20,4),coalesce(sini.cantidad,0)),
				importe=convert(numeric(20,4),coalesce(sini.importe,0)),
				costo=convert(numeric(20,4),coalesce(sini.costo,0)),
				smay.id_dmov, smay.fec_oper,  
				consecutivo = convert(int, null), smay.consecutivo_act,
				referencia = convert(char(10), '' ''),  
				id_oper = convert(int,null), fec_ent =Convert(datetime, null),
				orden = sini.id_smay, observaciones = Convert(varchar(5000),'' ''),
				id_unme = Case When smay.id_alma is not null 
				               Then arti.id_unme_al 
				               Else arti.id_unme_se End,
				cant_um = Case When smay.id_alma is not null 
				               Then arti.cant_unme_al 
				               Else arti.cant_unme_se End ,0,smay.Id_SMay
			FROM #Temporal smay
				INNER JOIN stoksini sini ON smay.id_smay = sini.id_smay 
				INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
			WHERE smay.id_dmov=0 ' + @Filtro_articulo + @filtro_destino

      Execute(@Cad)
   End
   
/* Fin obtener [Inventario Inicial] */   
-------------------------------------------------------------------------

--------------------------------------------------
/* 06 Inicio obtener [Informacion de Compras] */   
--------------------------------------------------
   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 1)
   Begin
      Select @Cad = 'INSERT #SUBMAYOR
		SELECT smay.id_alma, smay.id_secc, smay.id_arti, 
		cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
		cantidad = coalesce(cmpl.cantidad_D,0),
		importe = coalesce(cmpl.importe,0),
		costo = Round(Case When cmpl.cantidad_D = 0 
		                   Then  0 
		                   Else coalesce(cmpl.importe/cmpl.cantidad_D, 0) 
		                   End, 4),
		smay.id_dmov, smay.fec_oper,  
		oper.consecutivo, smay.consecutivo_act, oper.referencia,  
		oper.id_oper, oper.fec_ent, cmpl.orden, oper.observaciones,
		id_unme = Case When smay.id_alma is not null 
		               Then arti.id_unme_al 
		               Else arti.id_unme_se End,
		cant_um = Case When smay.id_alma is not null 
		               Then arti.cant_unme_al 
		               Else arti.cant_unme_se End ,0,smay.Id_SMay
	FROM #Temporal smay
		INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
		INNER JOIN stokscmp scmp ON scmp.id_smay=smay.id_smay
		INNER JOIN stokcmpl cmpl ON scmp.id_cmpl=cmpl.id_cmpl
		INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
	WHERE smay.id_dmov = 1 ' + 
		  Case When @id_tmov is not null 
		       Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
		       Else '' End + 
		   @Filtro_articulo + @filtro_destino 
     
      Execute(@Cad)
   End
/* Fin obtener [Informacion de Compras] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 07 Inicio obtener [Informacion de Reversiones de Compras] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 2)
Begin
  Select @Cad =  'INSERT #SUBMAYOR
		SELECT smay.id_alma, smay.id_secc, smay.id_arti, 
				cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
				cantidad = coalesce(-cmpl.cantidad_D,0),
				importe = coalesce(-cmpl.importe,0),
				costo = Round(Case When cmpl.cantidad_D = 0 
				                   Then  0 
				                   Else coalesce(cmpl.importe/cmpl.cantidad_D, 0)
				                   End, 4),
				smay.id_dmov, smay.fec_oper,  
				oper.consecutivo, smay.consecutivo_act, oper.referencia,  
				oper.id_oper, oper.fec_ent, cmpl.orden, oper.observaciones,
				id_unme = Case When smay.id_alma is not null 
				               Then arti.id_unme_al 
				               Else arti.id_unme_se End,
				cant_um = Case When smay.id_alma is not null 
				               Then arti.cant_unme_al 
				               Else arti.cant_unme_se End ,0,smay.Id_SMay
			FROM #Temporal smay
				INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
				INNER JOIN stokscmp scmp ON scmp.id_smay=smay.id_smay
				INNER JOIN stokcmpl cmpl ON scmp.id_cmpl=cmpl.id_cmpl
				INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
			WHERE smay.id_dmov = 2 ' + 
			      Case When @id_tmov is not null 
			           Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
			           Else '' End + 
			           @Filtro_articulo + @filtro_destino 

  Execute(@Cad)
End
/* Fin obtener [Informacion de Reversiones de Compras] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 08 Inicio obtener [Informacion de Devoluciones] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 32)
Begin
  Select @Cad = 'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti, 
				cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
				cantidad = coalesce(-cmpl.cantidad_D,0),
				importe = coalesce(-cmpl.importe,0),
				costo = Round(Case When cmpl.cantidad_D = 0 
				                   Then  0 
				                   Else coalesce(cmpl.importe/cmpl.cantidad_D, 0) 
				                   End, 4),
				smay.id_dmov, smay.fec_oper,  
				oper.consecutivo, smay.consecutivo_act, oper.referencia,  
				oper.id_oper, oper.fec_ent, cmpl.orden, oper.observaciones,
				id_unme = Case When smay.id_alma is not null 
				               Then arti.id_unme_al 
				               Else arti.id_unme_se End,
				cant_um = Case When smay.id_alma is not null 
				               Then arti.cant_unme_al 
				               Else arti.cant_unme_se End ,0,smay.Id_SMay
					FROM #Temporal smay
						INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
						INNER JOIN stoksdev scmp ON scmp.id_smay=smay.id_smay
						INNER JOIN stokdevl cmpl ON scmp.id_devl=cmpl.id_devl
						INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
					WHERE smay.id_dmov = 320 ' + 
						  Case When @id_tmov is not null 
						       Then 'and id_tmov = ' + 
								rtrim(ltrim(str(@id_tmov))) 
							   Else '' End + 
						  @Filtro_articulo + @filtro_destino 

  Execute(@Cad)
End
/* Fin obtener [Informacion de Devoluciones] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 09 Inicio obtener [Informacion de Traslados] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 3)
Begin
  Select @Cad =
    'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(CASE WHEN id_dmov = 31 
					                         THEN -tral.cantidad
							                 WHEN id_dmov = 32 
							                 THEN tral.cantidad_D END,0),
					importe = coalesce(CASE WHEN id_dmov = 31 
					                        THEN -tral.importe - tral.imp_desgaste
							                WHEN id_dmov = 32 
							                THEN tral.importe END,0),
					costo=round(case when id_dmov=31 
					                 then coalesce(tral.costo, 0)
								     else case when cantidad_d=0 
								          then 0 
										  else coalesce(tral.importe/tral.cantidad_D,0)    
										 end 
							     end,4),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = tral.id_tral, 
					oper.observaciones,
					id_unme = Case When smay.id_alma is not null 
					               Then arti.id_unme_al 
					               Else arti.id_unme_se End,
					cant_um = Case When smay.id_alma is not null 
					               Then arti.cant_unme_al 
					               Else arti.cant_unme_se End,0,smay.Id_SMay 
			FROM #Temporal smay
					INNER JOIN stokstra stra ON stra.id_smay = smay.id_smay
					INNER JOIN stoktral tral ON stra.id_tral = tral.id_tral
					INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
					INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
				WHERE smay.id_dmov IN (31,32) ' + 
				      Case When @id_tmov is not null 
				           Then 'and id_tmov = ' + 
						         rtrim(ltrim(str(@id_tmov)))
						    Else '' End + 
						@Filtro_articulo + @filtro_destino 

  Execute(@Cad)
End
/* Fin obtener [Informacion de Traslados] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 10 Inicio obtener [Informacion de Reversiones de Traslados] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 4)
Begin
  Select @Cad =  
		'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(CASE WHEN id_dmov = 41 
					                         THEN tral.cantidad
					                         WHEN id_dmov = 42 
					                         THEN -tral.cantidad_D END,0),
					importe = coalesce(CASE WHEN id_dmov = 41 
											THEN tral.importe + tral.imp_desgaste
											WHEN id_dmov = 42 
											THEN -tral.importe END,0),
					costo=round(case when id_dmov=41 
					            then coalesce(tral.costo, 0)
								else case when cantidad_d=0 
								          then 0 
										  else coalesce(tral.importe/tral.cantidad_D,0)    
								 end 
					            end,4),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = tral.id_tral, oper.observaciones,
					id_unme = Case When smay.id_alma is not null 
					               Then arti.id_unme_al 
					               Else arti.id_unme_se End,
					cant_um = Case When smay.id_alma is not null 
					               Then arti.cant_unme_al 
					               Else arti.cant_unme_se End ,0 ,smay.Id_SMay
				FROM #Temporal smay	
					INNER JOIN stokstra stra ON stra.id_smay = smay.id_smay
					INNER JOIN stoktral tral ON stra.id_tral = tral.id_tral
					INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
					INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
				WHERE smay.id_dmov IN (41,42) ' + 
						Case When @id_tmov is not null 
							 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
							 Else '' End + 
					@Filtro_articulo + @filtro_destino 
 
  Execute(@Cad)
End
/* Fin obtener [Informacion de Reversiones de Traslados] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 11 Inicio obtener [Informacion de Ajustes] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 5)
Begin
  Select @Cad =  
		'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(ajul.cantidad,0),
					importe = coalesce(ajul.importe,0), 
					costo = coalesce(ajul.costo, 0),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = ajul.id_ajul, oper.observaciones,
					id_unme = Case When smay.id_alma is not null 
					               Then arti.id_unme_al 
					               Else arti.id_unme_se End,
					cant_um = Case When smay.id_alma is not null 
					               Then arti.cant_unme_al 
					               Else arti.cant_unme_se End ,0,smay.Id_SMay
			FROM #Temporal smay
				INNER JOIN stoksaju saju ON saju.id_smay = smay.id_smay
				INNER JOIN stokajul ajul ON saju.id_ajul = ajul.id_ajul
				INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
				INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
			WHERE smay.id_dmov = 5  ' + Case When @id_tmov is not null Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) Else '' End + @Filtro_articulo + @filtro_destino 
			 
  Execute(@Cad)
End
/* Fin obtener [Informacion de Ajustes] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 12 Inicio obtener [Informacion de Reversiones de Ajustes] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 6)
Begin
  Select @Cad =  
		'INSERT #SUBMAYOR
				SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(-ajul.cantidad,0),
					importe = coalesce(-ajul.importe,0), 
					costo = coalesce(ajul.costo, 0),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = ajul.id_ajul, oper.observaciones,
					id_unme = Case	When smay.id_alma is not null 
									Then arti.id_unme_al 
									Else arti.id_unme_se End,
					cant_um = Case	When smay.id_alma is not null 
									Then arti.cant_unme_al 
									Else arti.cant_unme_se End,0 ,smay.Id_SMay 
			FROM #Temporal smay
				INNER JOIN stoksaju saju ON saju.id_smay = smay.id_smay
				INNER JOIN stokajul ajul ON saju.id_ajul = ajul.id_ajul
				INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
				INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
			WHERE smay.id_dmov = 6  ' +	
				Case When @id_tmov is not null 
						Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
						Else '' End + 
				@Filtro_articulo + @filtro_destino 
 
  Execute(@Cad)
End
/* Fin obtener [Informacion de Reversiones de Ajustes] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 13 Inicio obtener [Informacion de Fijación de inventarios] */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 9)
Begin
  Select @Cad =  
		'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
				cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
				cantidad = coalesce(invl.toma-invl.existencia,0),
				importe = coalesce(invl.importe,0),
				costo = coalesce(invl.costo, 0),
				smay.id_dmov, smay.fec_oper,  
				oper.consecutivo, smay.consecutivo_act, oper.referencia,  
				oper.id_oper, oper.fec_ent, orden, oper.observaciones,
				id_unme = Case	When smay.id_alma is not null 
								Then arti.id_unme_al 
								Else arti.id_unme_se End,
				cant_um = Case	When smay.id_alma is not null 
								Then arti.cant_unme_al
								Else arti.cant_unme_se End,0,smay.Id_SMay
			FROM #Temporal smay
				INNER JOIN stoksinv sinv ON sinv.id_smay = smay.id_smay
				INNER JOIN stokinvl invl ON sinv.id_invl = invl.id_invl
				INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
				INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
			WHERE smay.id_dmov = 9 ' + 
					Case When @id_tmov is not null 
						Then ' and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
						Else '' End + 
				@Filtro_articulo + @filtro_destino 
  Execute(@Cad)
End
/* Fin obtener [Informacion de Fijación de inventarios] */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 14 Inicio obtener [Informacion de Despieces */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 10)
Begin
  /* 14.1  (art. origen) */
  Select @Cad =  
  'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
			cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
			cantidad = coalesce(-dpc.cantidad,0),
			importe = coalesce(-dpc.importe,0),
			costo = coalesce(dpc.costo, 0),
			smay.id_dmov, smay.fec_oper,  
			oper.consecutivo, smay.consecutivo_act, oper.referencia,  
			oper.id_oper, oper.fec_ent, orden = dpc.id_operacion, oper.observaciones,
			id_unme = Case When smay.id_alma is not null 
							Then arti.id_unme_al
							Else arti.id_unme_se End,
			cant_um = Case When smay.id_alma is not null 
							Then arti.cant_unme_al 
							Else arti.cant_unme_se End ,0,smay.Id_SMay
		FROM #Temporal smay
			INNER JOIN stokdesc dpc ON dpc.id_operacion = smay.id_operacion
			INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
			INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
		WHERE smay.id_dmov = 101  ' + 
				Case When @id_tmov is not null 
					Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
					Else '' End + 
			@Filtro_articulo + @filtro_destino 

Execute(@Cad)

  /* 14.2 (arts. destino) */
  Select @Cad = 
	'INSERT #SUBMAYOR 
		SELECT smay.id_alma, smay.id_secc, smay.id_arti,
				cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
				cantidad = coalesce(desl.cantidad,0),
				importe = coalesce(desl.importe,0),
				costo = coalesce(desl.costo, 0),
				smay.id_dmov, smay.fec_oper,  
				oper.consecutivo, smay.consecutivo_act, oper.referencia,  
				oper.id_oper, oper.fec_ent, orden = desl.id_desl, oper.observaciones,
				id_unme = Case When smay.id_alma is not null 
				               Then arti.id_unme_al 
				               Else arti.id_unme_se End,
				cant_um = Case When smay.id_alma is not null 
				               Then arti.cant_unme_al 
				               Else arti.cant_unme_se End
				,0,smay.Id_SMay
		FROM #Temporal smay
			INNER JOIN stoksdel sdel ON sdel.id_smay = smay.id_smay
			INNER JOIN stokdesl desl ON desl.id_desl = sdel.id_desl
			INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
			INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
		WHERE smay.id_dmov = 102 ' + Case When @id_tmov is not null Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) Else '' End + @Filtro_articulo + @filtro_destino 

  Execute(@Cad)
End
/* Fin obtener [Informacion de Despieces */   
-----------------------------------------------------------------------

-----------------------------------------------------------------------
/* 15 Inicio obtener [Informacion de Reversiones de Despieces */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 11)
Begin
  /* 15.1 (art. origen) */
  Select @Cad =  
		'INSERT #SUBMAYOR
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
			cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,		cantidad = coalesce(dpc.cantidad,0),
			importe = coalesce(dpc.importe,0),
			costo = coalesce(dpc.costo, 0),
			smay.id_dmov, smay.fec_oper,  
			oper.consecutivo, smay.consecutivo_act, oper.referencia,  
			oper.id_oper, oper.fec_ent, orden = dpc.id_operacion, oper.observaciones,
			id_unme = Case When smay.id_alma is not null 
			               Then arti.id_unme_al 
			               Else arti.id_unme_se End,
			cant_um = Case When smay.id_alma is not null 
						   Then arti.cant_unme_al 
						   Else arti.cant_unme_se End
			,0 ,smay.Id_SMay 
		FROM #Temporal smay
			INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
			INNER JOIN stokdesc dpc ON dpc.id_operacion = oper.id_revertido
			INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
		WHERE smay.id_dmov = 111 ' + 
				Case When @id_tmov is not null 
					 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
					 Else '' End + 
			 @Filtro_articulo + @filtro_destino 
 
  Execute(@Cad)

  /* 15.2 (arts. destino) */ 
  Select @Cad = 
		'INSERT #SUBMAYOR 
			SELECT smay.id_alma, smay.id_secc, smay.id_arti,
				cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
				cantidad = coalesce(-desl.cantidad,0),
				importe = coalesce(-desl.importe,0),
				costo = coalesce(desl.costo, 0),
				smay.id_dmov, smay.fec_oper,  
				oper.consecutivo, smay.consecutivo_act, oper.referencia,  
				oper.id_oper, oper.fec_ent, orden = desl.id_desl, oper.observaciones,
				id_unme = Case When smay.id_alma is not null 
							   Then arti.id_unme_al 
							   Else arti.id_unme_se End,
				cant_um = Case When smay.id_alma is not null 
							   Then arti.cant_unme_al 
							   Else arti.cant_unme_se End
				,0,smay.Id_SMay
		FROM #Temporal smay
			INNER JOIN stoksdel sdel ON sdel.id_smay = smay.id_smay
			INNER JOIN stokdesl desl ON desl.id_desl = sdel.id_desl
			INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
			INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
		WHERE smay.id_dmov = 112 ' + 
				Case When @id_tmov is not null 
					 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
					 Else '' End + @Filtro_articulo + @filtro_destino 

  Execute(@Cad)
End
/* Fin obtener [Informacion de Reversiones de Despieces */   
---------------------------------------------------------------------

/* 16 Inicio obtener [Informacion de Rebaja Automatica */   
-----------------------------------------------------------------------
If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 12)
Begin
  /* 16.1  principal */
  Select @Cad =  'INSERT #SUBMAYOR
	SELECT smay.id_alma, smay.id_secc, smay.id_arti,
	cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
	cantidad = coalesce(-rebp.cantidad,0),
	importe = coalesce(-rebp.importe,0),
	costo = coalesce(rebp.costo,0),
	smay.id_dmov, smay.fec_oper,  
	oper.consecutivo, smay.consecutivo_act, oper.referencia,  
	oper.id_oper, oper.fec_ent, orden = rebp.id_rebp, oper.observaciones,
	id_unme = Case When smay.id_alma is not null 
				   Then arti.id_unme_al 
				   Else arti.id_unme_se End,
	cant_um = Case When smay.id_alma is not null 
	               Then arti.cant_unme_al 
	               Else arti.cant_unme_se End  
	,0,smay.Id_SMay
FROM #Temporal smay
	INNER JOIN stoksrep srep ON srep.id_smay = smay.id_smay
	INNER JOIN stokrebp rebp ON srep.id_rebp = rebp.id_rebp
	INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
	INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
WHERE smay.id_dmov = 121  ' + 
       Case When @id_tmov is not null 
            Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
            Else '' End + @Filtro_articulo + @filtro_destino
 
  Execute(@Cad)

  /* 16.2 alternativo */
  Select @Cad = 'INSERT #SUBMAYOR 
	SELECT smay.id_alma, smay.id_secc, smay.id_arti,
	cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
	cantidad = coalesce(-reba.cantidad,0),
	importe = coalesce(-reba.importe,0),
	costo = coalesce(reba.costo,0),
	smay.id_dmov, smay.fec_oper,  
	oper.consecutivo, smay.consecutivo_act, oper.referencia,  
	oper.id_oper, oper.fec_ent, orden, oper.observaciones,
	id_unme = Case When smay.id_alma is not null 
	               Then arti.id_unme_al 
	               Else arti.id_unme_se End,
	cant_um = Case When smay.id_alma is not null 
	               Then arti.cant_unme_al 
	               Else arti.cant_unme_se End
	,0,smay.Id_SMay
FROM #Temporal smay
	INNER JOIN stoksrea srea ON srea.id_smay = smay.id_smay
	INNER JOIN stokreba reba ON srea.id_reba = reba.id_reba
	INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
	INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
WHERE smay.id_dmov = 122  ' + 
        Case When @id_tmov is not null 
             Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
             Else '' End + @Filtro_articulo + @filtro_destino 

  Execute(@Cad)

End

-----------------------------------------------------------------------
/* 16.2  Cambio de código */
-----------------------------------------------------------------------
   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 13)
   Begin
      /* 16.2.1  destino */
      Select @Cad =  'INSERT #SUBMAYOR
		SELECT smay.id_alma, smay.id_secc, smay.id_arti,
		cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
		cantidad = coalesce(camr.cantidad,0),
		importe = coalesce(camr.importe,0),
		costo = coalesce(camr.costo,0),
		smay.id_dmov, smay.fec_oper,  
		oper.consecutivo, smay.consecutivo_act, oper.referencia,  
		oper.id_oper, oper.fec_ent, orden = camr.id_camr, oper.observaciones,
		id_unme = Case When smay.id_alma is not null 
					   Then arti.id_unme_al 
					   Else arti.id_unme_se End,
		cant_um = Case	When smay.id_alma is not null 
						Then arti.cant_unme_al 
						Else arti.cant_unme_se End  
		,0,smay.Id_SMay
	FROM #Temporal smay
		INNER JOIN stokscmr scmr ON scmr.id_smay = smay.id_smay
		INNER JOIN stokcamr camr ON scmr.id_camr = camr.id_camr
		INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
		INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
	WHERE smay.id_dmov = 131  ' + 
			Case When @id_tmov is not null 
				 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
				 Else '' End + @Filtro_articulo + @filtro_destino 
     
      Execute(@Cad)

      /* 16.3 orígenes  */
      Select @Cad = 'INSERT #SUBMAYOR 
		SELECT smay.id_alma, smay.id_secc, smay.id_arti,
		cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
		cantidad = coalesce(-carl.cantidad,0),
		importe = coalesce(-carl.importe,0),
		costo = coalesce(carl.costo,0),
		smay.id_dmov, smay.fec_oper,  
		oper.consecutivo, smay.consecutivo_act, oper.referencia,  		oper.id_oper, oper.fec_ent, orden = carl.id_carl, oper.observaciones,
		id_unme = Case	When smay.id_alma is not null 
						Then arti.id_unme_al 
						Else arti.id_unme_se End,
		cant_um = Case	When smay.id_alma is not null 
						Then arti.cant_unme_al 
						Else arti.cant_unme_se End
		,0,smay.Id_SMay
	FROM #Temporal smay
		INNER JOIN stokscml scml ON scml.id_smay = smay.id_smay
		INNER JOIN stokcarl carl ON scml.id_carl = carl.id_carl
		INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
		INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
	WHERE smay.id_dmov  =132  ' + 
			Case When @id_tmov is not null 
				 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
				 Else '' End + @Filtro_articulo + @filtro_destino 

      Execute(@Cad)
   End

-----------------------------------------------------------------------
/* 17 Cambios de UM, orígenes y destinos */
-----------------------------------------------------------------------
   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 14)
   Begin
      Select @Cad =  'INSERT #SUBMAYOR
		SELECT smay.id_alma, smay.id_secc, smay.id_arti,
		cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
		cantidad = coalesce(CASE WHEN id_dmov = 141 THEN -scmu.cantidad 
  	 		 ELSE scmu.cantidad END,0),
		importe = coalesce(CASE WHEN id_dmov = 141 THEN -scmu.importe 
			 ELSE scmu.importe END,0),
		costo = Round(Case When scmu.cantidad = 0 Then 0 Else coalesce(scmu.importe/scmu.cantidad,0) End,4),
		smay.id_dmov, smay.fec_oper,  
		oper.consecutivo, smay.consecutivo_act, oper.referencia,  
		oper.id_oper, oper.fec_ent, orden = scmu.id_smay, oper.observaciones,
		id_unme = Case	When smay.id_alma is not null 
						Then arti.id_unme_al 
						Else arti.id_unme_se End,
		cant_um = Case	When smay.id_alma is not null 
						Then arti.cant_unme_al 
						Else arti.cant_unme_se End  
		,0,smay.Id_SMay
	FROM #Temporal smay
		INNER JOIN stokscmu scmu ON scmu.id_smay = smay.id_smay
		INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
		INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
	WHERE smay.id_dmov IN (141,142) ' + 
				Case When @id_tmov is not null 
					 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov)))
					 Else '' End + @Filtro_articulo + @filtro_destino 
     
      Execute(@Cad)
   End

-----------------------------------------------------------------------
/* 18 Traslados multialmacen enviados y recibidos */
-----------------------------------------------------------------------
   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 7)
   Begin
      Select @Cad =  'INSERT #SUBMAYOR
		SELECT smay.id_alma, smay.id_secc, smay.id_arti,
		cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
		 cantidad = coalesce(CASE WHEN id_dmov = 71 THEN -tral.cantidad
						 WHEN id_dmov = 72 THEN tral.cantidad_D END,0),
		importe = coalesce(CASE WHEN id_dmov = 71 THEN -tral.importe - tral.imp_desgaste
						WHEN id_dmov = 72 THEN tral.importe END,0),
		costo = coalesce(tral.costo, 0),
		smay.id_dmov, smay.fec_oper,  
		oper.consecutivo, smay.consecutivo_act, oper.referencia,  
		oper.id_oper, oper.fec_ent, orden = tral.id_mall, oper.observaciones,
		id_unme = Case	When smay.id_alma is not null 
						Then arti.id_unme_al
						Else arti.id_unme_se End,
		cant_um = Case	When smay.id_alma is not null 
						Then arti.cant_unme_al 
						Else arti.cant_unme_se End  
		,0,smay.Id_SMay
	FROM #Temporal smay
		INNER JOIN stoksmal stra ON stra.id_smay = smay.id_smay
		INNER JOIN stokmall tral ON stra.id_mall = tral.id_mall
		INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
		INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
	WHERE smay.id_dmov IN (71,72)  ' + 
			Case When @id_tmov is not null 
				 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov)))
				 Else '' End + @Filtro_articulo + @filtro_destino 
     
      Execute(@Cad)
   End
   
-----------------------------------------------------------------------
/* 19  Elaboraciones */
-----------------------------------------------------------------------
   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 15)
	   Begin
	      /* 19.1  (elaborado) */
	      Select @Cad =  'INSERT #SUBMAYOR
				SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(dpc.cant_r,0),
					importe = coalesce(dpc.importe,0),
					costo = coalesce(dpc.costo, 0),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = dpc.id_operacion, oper.observaciones,
					id_unme = Case  When smay.id_alma is not null 
									Then arti.id_unme_al 
									Else arti.id_unme_se End,
					cant_um = Case	When smay.id_alma is not null 
									Then arti.cant_unme_al 
									Else arti.cant_unme_se End   
					,0,smay.Id_SMay
				FROM #Temporal smay
					INNER JOIN stokeelo dpc ON dpc.id_operacion = smay.id_operacion
					INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
					INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
				WHERE smay.id_dmov = 152  ' + 
						Case When @id_tmov is not null 
							 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov)))
							 Else '' End + @Filtro_articulo + @filtro_destino 
	      Execute(@Cad)
	      
	      /* 19.2 (ingredientes)  */
	      Select @Cad = 'INSERT #SUBMAYOR 
				SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(-desl.cant_r,0),
					importe = coalesce(-desl.importe,0),
					costo = coalesce(desl.costo, 0),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = desl.id_eell, oper.observaciones,
					id_unme = Case	When smay.id_alma is not null 
									Then arti.id_unme_al 
									Else arti.id_unme_se End,
					cant_um = Case	When smay.id_alma is not null 
									Then arti.cant_unme_al 
									Else arti.cant_unme_se End
					,0,smay.Id_SMay
				FROM #Temporal smay
					INNER JOIN stokseel sdel ON sdel.id_smay = smay.id_smay
					INNER JOIN stokeell desl ON desl.id_eell = sdel.id_eell
					INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
					INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
				WHERE smay.id_dmov = 151 ' + 
						Case When @id_tmov is not null 
							 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov)))
							 Else '' End + @Filtro_articulo + @filtro_destino 
	      Execute(@Cad)
   End
-----------------------------------------------------------------------
/* 20  Reversion de Elaboraciones */
-----------------------------------------------------------------------
   If (@id_tmov is NULL) or (@id_tmov is not NULL and @id_cmov = 16)
	   Begin
	      /* 20.1 (elaborado) */
	      Select @Cad =  'INSERT #SUBMAYOR
				SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,					cantidad = coalesce(-dpc.cant_r,0),
					importe = coalesce(-dpc.importe,0),
					costo = coalesce(dpc.costo, 0),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = dpc.id_operacion, oper.observaciones,
					id_unme = Case	When smay.id_alma is not null 
									Then arti.id_unme_al 
									Else arti.id_unme_se End,
					cant_um = Case	When smay.id_alma is not null 
									Then arti.cant_unme_al 
									Else arti.cant_unme_se End  
					,0,smay.Id_SMay
				FROM #Temporal smay
					INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
					INNER JOIN stokeelo dpc ON dpc.id_operacion = oper.id_revertido
					INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
				WHERE smay.id_dmov = 162 ' + 
						Case When @id_tmov is not null 
							 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov))) 
							 Else '' End + @Filtro_articulo + @filtro_destino 
	      Execute(@Cad)
	      
	      /* 20.2 (ingredientes) */ 
	      Select @Cad = 'INSERT #SUBMAYOR 
				SELECT smay.id_alma, smay.id_secc, smay.id_arti,
					cod_arti = arti.FullArtiCode, desc_arti = arti.descripcion,
					cantidad = coalesce(desl.cant_r,0),
					importe = coalesce(desl.importe,0),
					costo = coalesce(desl.costo, 0),
					smay.id_dmov, smay.fec_oper,  
					oper.consecutivo, smay.consecutivo_act, oper.referencia,  
					oper.id_oper, oper.fec_ent, orden = desl.id_eell, oper.observaciones,
					id_unme = Case	When smay.id_alma is not null 
									Then arti.id_unme_al 
									Else arti.id_unme_se End,
					cant_um = Case	When smay.id_alma is not null 
									Then arti.cant_unme_al 
									Else arti.cant_unme_se End
					,0,smay.Id_SMay
				FROM #Temporal smay
					INNER JOIN stokseel sdel ON sdel.id_smay = smay.id_smay
					INNER JOIN stokeell desl ON desl.id_eell = sdel.id_eell
					INNER JOIN stokarti arti ON smay.id_arti = arti.id_arti
					INNER JOIN stokoper oper ON smay.id_operacion = oper.id_operacion
				WHERE smay.id_dmov = 161 ' + 
						Case When @id_tmov is not null 
							 Then 'and id_tmov = ' + rtrim(ltrim(str(@id_tmov)))
							 Else '' End + @Filtro_articulo + @filtro_destino 
	      Execute(@Cad)
   	End

--/* 21 Esto se bloque, dado que ya no lo necesita, esto lo realiza cuando pasa
--la informacion a la tabla [#Temporal]
--*/
------   If @fdesde is not null and @fhasta is not null
------   Begin
------		-- Para almacén
------		Select su.*, cod_alma = alma.codigo, desc_alma = alma.descripcion, 
------			cod_secc =convert(char(3),null), desc_secc = convert(varchar(40),null) ,
------			cod_unme = unme.codigo, desc_unme = unme.descripcion,
------			stock_max = Coalesce(alex.stock_max, 0),
------			stock_min = Coalesce(alex.stock_min, 0),
------			existencia = Coalesce(alex.existencia, 0),
------			cod_dest = 'A' + alma.codigo,
------			cod_dmov = dmov.codigo, desc_dmov = dmov.descripcion, op.nombre
------		From #SUBMAYOR su
------			Inner Join stokalma alma On su.id_alma = alma.id_alma
------			Inner Join stokunme unme On su.id_unme = unme.id_unme
------			Left Join stokalex alex On su.id_arti = alex.id_arti and su.id_alma = alex.id_alma
------			Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
------			Left Join operador op On su.id_oper = op.id_oper
------		Where su.id_alma is not null and 
------			Datediff(dy, @fdesde, fec_oper) >= 0 and Datediff(dy, fec_oper, @fhasta) >= 0
------		-- Para sección
------		UNION ALL
------      Select su.*, cod_alma = convert(char(2),null), desc_alma = convert(varchar(40),null), 
------			cod_secc = secc.codigo, desc_secc = secc.descripcion ,
------			cod_unme = unme.codigo, desc_unme = unme.descripcion,
------			stock_max = Coalesce(seex.stock_max, 0),
------			stock_min = Coalesce(seex.stock_min, 0),
------         existencia = Coalesce(seex.existencia, 0),
------			cod_dest = 'S' + secc.codigo,
------			cod_dmov = dmov.codigo, desc_dmov = dmov.descripcion, op.nombre
------      From #SUBMAYOR su
------         inner Join stoksecc secc On su.id_secc = secc.id_secc
------         Inner Join stokunme unme On su.id_unme = unme.id_unme
------         Left Join stokseex seex On su.id_arti = seex.id_arti and su.id_secc = seex.id_secc
------         Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
------         Left Join operador op On su.id_oper = op.id_oper
------		Where su.id_alma is null and 
------			Datediff(dy, @fdesde, fec_oper) >= 0 and Datediff(dy, fec_oper, @fhasta) >= 0
------		Order By cod_dest, cod_arti, consecutivo_act, fec_oper, orden
------   End
------   Else
------      If  @fdesde is not null
------      Begin
------			-- Para almacén
------			Select su.*, cod_alma = alma.codigo, desc_alma = alma.descripcion, 
------				cod_secc =convert(char(3),null), desc_secc = convert(varchar(40),null) ,
------				cod_unme = unme.codigo, desc_unme = unme.descripcion,
------				stock_max = Coalesce(alex.stock_max, 0),
------				stock_min = Coalesce(alex.stock_min, 0),
------				existencia = Coalesce(alex.existencia, 0),
------				cod_dest = 'A' + alma.codigo,
------				cod_dmov = dmov.codigo, desc_dmov = dmov.descripcion, op.nombre
------			From #SUBMAYOR su
------				Inner Join stokalma alma On su.id_alma = alma.id_alma
------				Inner Join stokunme unme On su.id_unme = unme.id_unme
------				Left Join stokalex alex On su.id_arti = alex.id_arti and su.id_alma = alex.id_alma
------				Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
------				Left Join operador op On su.id_oper = op.id_oper
------			Where su.id_alma is not null and 
------				Datediff(dy, @fdesde, fec_oper) >= 0
------			-- Para sección
------			UNION ALL
------	      Select su.*, cod_alma = convert(char(2),null), desc_alma = convert(varchar(40),null), 
------				cod_secc = secc.codigo, desc_secc = secc.descripcion ,
------				cod_unme = unme.codigo, desc_unme = unme.descripcion,
------				stock_max = Coalesce(seex.stock_max, 0),
------				stock_min = Coalesce(seex.stock_min, 0),
------	         existencia = Coalesce(seex.existencia, 0),
------				cod_dest = 'S' + secc.codigo,
------				cod_dmov = dmov.codigo, desc_dmov = dmov.descripcion, op.nombre
------	      From #SUBMAYOR su
------	         inner Join stoksecc secc On su.id_secc = secc.id_secc
------	         Inner Join stokunme unme On su.id_unme = unme.id_unme
------	         Left Join stokseex seex On su.id_arti = seex.id_arti and su.id_secc = seex.id_secc
------	         Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
------	         Left Join operador op On su.id_oper = op.id_oper
------			Where su.id_alma is null and 
------				Datediff(dy, @fdesde, fec_oper) >= 0			
------			Order By cod_dest, cod_arti, consecutivo_act, fec_oper, orden
------      End
------      Else
------         If @fhasta is not null
------         Begin
------				-- Para almacén
------				Select su.*, cod_alma = alma.codigo, desc_alma = alma.descripcion, 
------					cod_secc =convert(char(3),null), desc_secc = convert(varchar(40),null) ,
------					cod_unme = unme.codigo, desc_unme = unme.descripcion,
------					stock_max = Coalesce(alex.stock_max, 0),
------					stock_min = Coalesce(alex.stock_min, 0),
------					existencia = Coalesce(alex.existencia, 0),
------					cod_dest = 'A' + alma.codigo,
------					cod_dmov = dmov.codigo, desc_dmov = dmov.descripcion, op.nombre
------				From #SUBMAYOR su
------					Inner Join stokalma alma On su.id_alma = alma.id_alma
------					Inner Join stokunme unme On su.id_unme = unme.id_unme
------					Left Join stokalex alex On su.id_arti = alex.id_arti and su.id_alma = alex.id_alma
------					Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
------					Left Join operador op On su.id_oper = op.id_oper
------				Where su.id_alma is not null and 
------					Datediff(dy, fec_oper, @fhasta) >= 0
------				-- Para sección
------				UNION ALL
------		      Select su.*, cod_alma = convert(char(2),null), desc_alma = convert(varchar(40),null), 
------					cod_secc = secc.codigo, desc_secc = secc.descripcion ,
------					cod_unme = unme.codigo, desc_unme = unme.descripcion,
------					stock_max = Coalesce(seex.stock_max, 0),
------					stock_min = Coalesce(seex.stock_min, 0),
------		         existencia = Coalesce(seex.existencia, 0),
------					cod_dest = 'S' + secc.codigo,
------					cod_dmov = dmov.codigo, desc_dmov = dmov.descripcion, op.nombre
------		      From #SUBMAYOR su
------		         inner Join stoksecc secc On su.id_secc = secc.id_secc
------		         Inner Join stokunme unme On su.id_unme = unme.id_unme
------		         Left Join stokseex seex On su.id_arti = seex.id_arti and su.id_secc = seex.id_secc
------		         Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
------		         Left Join operador op On su.id_oper = op.id_oper
------				Where su.id_alma is null and 
------					Datediff(dy, fec_oper, @fhasta) >= 0
------				Order By cod_dest, cod_arti, consecutivo_act, fec_oper, orden
------	    	End
------         Else
------         Begin

-------------------------------
/* 22 Para almacén */
-------------------------------
Select su.*, cod_alma = alma.codigo, 
       desc_alma = alma.descripcion, 
	   cod_secc =convert(char(3),null), 
	   desc_secc = convert(varchar(40),null) ,
	   cod_unme = unme.codigo, desc_unme = unme.descripcion,
	   stock_max = Coalesce(alex.stock_max, 0),
	   stock_min = Coalesce(alex.stock_min, 0),
       existencia = Coalesce(alex.existencia, 0),
	   cod_dest = 'A' + alma.codigo,
	   cod_dmov = dmov.codigo, 
	   desc_dmov = dmov.descripcion, op.nombre
    Into #Temp1 
    From #SUBMAYOR su
         inner Join stokalma alma On su.id_alma = alma.id_alma
         Inner Join stokunme unme On su.id_unme = unme.id_unme
         Left Join stokalex alex On su.id_arti = alex.id_arti 
               and su.id_alma = alex.id_alma
         Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
         Left Join operador op On su.id_oper = op.id_oper
	Where su.id_alma is not null
	
	/* 22.1 Para sección */
	UNION ALL
   Select su.*, cod_alma = convert(char(2),null), 
          desc_alma = convert(varchar(40),null), 
		  cod_secc = secc.codigo, 
		  desc_secc = secc.descripcion ,
		  cod_unme = unme.codigo, 
		  desc_unme = unme.descripcion,
		  stock_max = Coalesce(seex.stock_max, 0),
		  stock_min = Coalesce(seex.stock_min, 0),
          existencia = Coalesce(seex.existencia, 0),
		  cod_dest = 'S' + secc.codigo,
		  cod_dmov = dmov.codigo,
		  desc_dmov = dmov.descripcion, op.nombre
      From #SUBMAYOR su
           inner Join stoksecc secc On su.id_secc = secc.id_secc
           Inner Join stokunme unme On su.id_unme = unme.id_unme
           Left Join stokseex seex On su.id_arti = seex.id_arti 
                 and su.id_secc = seex.id_secc
           Inner Join stokdmov dmov On su.id_dmov = dmov.id_dmov
           Left Join operador op On su.id_oper = op.id_oper
		Where su.id_alma is null
	    Order By cod_dest, cod_arti, 
	             consecutivo_act, fec_oper, orden,IdSmay
--         End

/* */

 --Declare @NomTabla nvarchar(100)
 --Select @NomTabla = 'TempS' + HOST_NAME()
 --Declare @vSql nvarchar(500)
 --exec Existe_TablaSaldo



Insert Into #TempSaldos
        Select id_Arti,
                 Case when Id_Alma is null 
                      Then 0 
                      else Id_Alma end,
                 Case When Id_Secc is null
                      Then 0
                      Else Id_Secc end,
                 Cantidad = dbo.FSaldo_CantidadW(id_arti,id_alma,Id_secc,@FDesde),
				 Importe  = dbo.FSaldo_ImporteW(id_arti,id_alma,Id_secc,@FDesde)
                 --Cantidad = dbo.FSaldo_CantidadN(id_arti,id_alma,Id_secc,@FDesde),
                 --Importe  = dbo.FSaldo_ImporteN(id_arti,id_alma,Id_secc,@FDesde)
                 --Cantidad = dbo.FSaldo_Cantidad(id_arti,id_alma,Id_secc,@FDesde),
                 --Importe  = dbo.FSaldo_Importe(id_arti,id_alma,Id_secc,@FDesde)
              from #Temp1 
       Group by cod_arti,id_Arti,Id_Alma,id_Secc,idsmay 
       
--Select @vSql = ' Insert Into ' + @NomTabla +
--               ' Select * from #tempSaldos '       
--Exec (@vSql)
--select * from TempSCHOROTEGA

Delete SaldoSubMayor
  Where id_term = @IdTerminal

Insert Into SaldoSubMayor
   Select @IdTerminal,* 
      From #TempSaldos

Update #Temp1 Set id_alma= 0 where id_alma is null
Update #Temp1 Set id_secc= 0 where id_secc is null 

Select * 
   From #Temp1             
   order by cod_arti,Id_Alma,id_Secc,fec_oper,fec_ent
   
--Select * 
--   into Temp_SM_01
--   From #Temp1             
--   order by cod_arti,Id_Alma,id_Secc,fec_oper,fec_ent
   
   

END