IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'TIPOPARAM_DRO' AND
                 TYPE = 'FN' 		      AND
	              U.UID = O.UID           AND
	              U.NAME = USER)
DROP FUNCTION TIPOPARAM_DRO
GO

CREATE FUNCTION TIPOPARAM_DRO( @P_CDFILIAL  VARCHAR(04))
RETURNS VARCHAR(04)
AS
BEGIN

   DECLARE @V_CDFILIPDR       VARCHAR(04);
   DECLARE @V_IDUTPADRROPFIL  VARCHAR(1);

   SET @V_CDFILIPDR  = 'P';

     SELECT @V_CDFILIPDR = MAX('P')
     FROM PARAMGERAL
     WHERE IDUTPADRROP = 'S';

   IF @V_CDFILIPDR IS NULL  BEGIN
      SELECT @V_CDFILIPDR = MAX('P')
        FROM PARFILIALROP
        WHERE ISNULL(IDUTPADRROPFIL,'N') = 'S'
          AND CDFILIAL = @P_CDFILIAL;

      IF @V_CDFILIPDR IS NULL BEGIN

         SET @V_CDFILIPDR = Null;

         SELECT @V_CDFILIPDR = MAX(CDFILIAL)
           FROM
               (SELECT P.CDFILIAL
                 FROM FILIAL F, PARFILIALROP P
                WHERE F.CDFILIAL = @P_CDFILIAL
                  AND F.CDFILIAL = P.CDFILIAL
                  AND CDFILCENTPME IS NULL

               UNION ALL

               SELECT F.CDFILIAL
                 FROM FILIAL F
                 LEFT JOIN PARFILIALROP P
                   ON CDFILCENTPME = P.CDFILIAL
                WHERE F.CDFILIAL = @P_CDFILIAL
                  AND CDFILCENTPME IS NOT NULL
                  AND ISNULL(P.IDFILIALAGRROP,'N') = 'N') A;


         IF @V_CDFILIPDR  IS NULL BEGIN
            SELECT @V_CDFILIPDR = MAX(CDFILCENTPME), @V_IDUTPADRROPFIL = MAX(IDUTPADRROPFIL)
              FROM FILIAL F, PARFILIALROP P
              WHERE F.CDFILIAL   = @P_CDFILIAL
                AND CDFILCENTPME = P.CDFILIAL
                AND ISNULL(P.IDFILIALAGRROP,'N') = 'S';

            IF @V_IDUTPADRROPFIL = 'S' BEGIN
               SET @V_CDFILIPDR = 'P' ;
            END;
         END;
      END;
   END;
   RETURN(@V_CDFILIPDR);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'TIPOPARAM_DRO','5.09.000';
GO
