-- dbo.ef_Vyroba_EvidROpR_MamNeuzavrenouPredchozi
CREATE FUNCTION dbo.ef_Vyroba_EvidROpR_MamNeuzavrenouPredchozi (@IDPrikaz INT, @Doklad INT, @Alt NCHAR(1) )
 RETURNS BIT
AS
 BEGIN
  DECLARE
   @retVal BIT=0,
   @sCisOper NVARCHAR(4),
   @iCisOper INT
  DECLARE @idPredOperaci TABLE (ID INT NOT NULL)


  SET @sCisOper=(SELECT TOP(1) TRIM(Operace) FROM dbo.TabPrPostup WITH(NOLOCK) WHERE IDPrikaz=@IDPrikaz AND Doklad=@Doklad AND Alt=@Alt AND IDOdchylkyDo IS NULL)
  SET @iCisOper=TRY_PARSE(@sCisOper AS INT)
  IF (@iCisOper IS NOT NULL)
   BEGIN
-- zjisti IDcka operaci prede mnou (dle cisla operace)
    INSERT @idPredOperaci (ID)
     SELECT ID FROM dbo.TabPrPostup WITH(NOLOCK) WHERE IDPrikaz=@IDPrikaz AND IDOdchylkyDo IS NULL AND ISNULL(TRY_PARSE(TRIM(Operace) AS INT),0)<@iCisOper

-- jsou operace prede mnou ?
    IF EXISTS(SELECT 1 FROM @idPredOperaci)
-- je nejaka co mam rozjetou v Evid.rozprac.operaci ?
     IF EXISTS (SELECT 1 FROM dbo.TabEvidRozpracOperR r WITH(NOLOCK) JOIN dbo.TabEvidRozpracOper h WITH(NOLOCK) ON (h.ID=r.IDEvidRozpracOper)
                  JOIN dbo.TabPrPostup p WITH(NOLOCK) ON (p.IDPrikaz=@IDPrikaz AND p.IDOdchylkyDo IS NULL)
                 WHERE p.ID IN (SELECT ID FROM @idPredOperaci) AND h.Stav IN (10,20)
               )
      SET @retVal=1
   END
  RETURN @retVal 
 END
