CREATE FUNCTION CF_Produc_Ocup_Cbte(@Id_Producto VARCHAR(14),@Fecha DATETIME) 
RETURNS INT
AS
BEGIN

DECLARE @Id_Trans INT

SET @Id_Trans = (SELECT TOP 1 A.Id_Trans FROM Cbtes_Items A, Cbtes B ,Cbtes_Tipos C 
                          WHERE A.Id_Trans = B.Id_Trans 
                          AND B.Id_Tipo_Cbte = C.Id_Tipo_Cbte 
                          AND A.Flag_QA = 'A' AND B.Id_Estado_Cbte NOT IN (0,3)
                          AND (C.Compromete_Factura = 1 OR C.Compromete_Remitos = 1 OR C.Compromete_Pedido = 1) 
                          AND A.Fecha_QA <= @Fecha + 1 AND ISNULL(A.Fecha_Venc,@Fecha +1) >= @Fecha - 1
                          AND A.Id_Producto = @Id_Producto 
						  ORDER BY A.Id_Trans DESC )
RETURN ISNULL(@Id_Trans,0)
END

