ALTER procedure [dbo].[_AdicionalesDespacho]	
@p_idalquiler as INT 

as begin

select 
itemalq.id,
itemalq.itemdocumento as adicional, 
itemalq.id_catalogo,
itemalq.cantidadplaneado as cantalq,
CASE 
WHEN 
(select SUM( despa.cantidadPlaneado) from  doc_itemdocumento as despa  
inner join doc_documento as salidas on salidas.id = despa.id_documento 
inner join doc_documento as entradas on entradas.id = despa.id_documento 
inner join cat_catalogo as cata on cata.id=despa.id_catalogo
inner join doc_estadoTipoDocumento on doc_estadoTipoDocumento.id=salidas.id_estadoTipoDocumento
where   cata.id=cat.id  and    
despa.id_itemDocumento=itemalq.id  and despa.active=1 and 
doc_estadoTipoDocumento.estadoTipoDocumento_codigo not like 'CAN'  and id_tipodocumento in (5,6))
    IS NULL
   THEN 0 
   ELSE
(select SUM( despa.cantidadPlaneado) from  doc_itemdocumento as despa  
inner join doc_documento as salidas on salidas.id = despa.id_documento 
inner join doc_documento as entradas on entradas.id = despa.id_documento 
inner join cat_catalogo as cata on cata.id=despa.id_catalogo
inner join doc_estadoTipoDocumento on doc_estadoTipoDocumento.id=salidas.id_estadoTipoDocumento
   where   cata.id=cat.id  and    
   despa.id_itemDocumento=itemalq.id  and despa.active=1 and 
   doc_estadoTipoDocumento.estadoTipoDocumento_codigo not like 'CAN'  and id_tipodocumento in (5,6))
   END as despachado      
from doc_itemDocumento as itemalq 
inner join cat_catalogo as cat on cat.id=itemalq.id_catalogo
 where  
itemalq.id_documento=@p_idalquiler
and (itemalq.id_catalogo in (select id from [cat_catalogo.otro] where active=1 and periodoalquiler<1 ) or  
 itemalq.id_catalogo in (select id from [cat_catalogo.repuesto]where active= 1) ) 
  and   itemalq.active=1 
  and itemalq.id_catalogo not in (select id_catalogo from equ_detallealquiler where active=1 and [id_documento.alquiler] = @p_idalquiler and id_Catalogo>0 )
  end