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

CREATE FUNCTION BUSCA_PRECOBASE( @P_CDFILIAL   VARCHAR(4),
                                 @P_CDCLIENTE  VARCHAR(21),
                                 @P_CDVENDEDOR VARCHAR(4),
                                 @P_CDMODPGTO  VARCHAR(5))RETURNS VARCHAR(2)
AS
BEGIN
  DECLARE @V_CTREGISTRO INTEGER;
  DECLARE @V_CDPRECOBASE VARCHAR(2);

   SET @V_CDPRECOBASE = '';
   SELECT @V_CTREGISTRO = COUNT(CDPRECOBASE) 
      FROM PRECOBASECLI
      WHERE CDCLIENTE = @P_CDCLIENTE
        AND IDPRBASEPRIN = 'S';

   IF @V_CTREGISTRO > 0 BEGIN
      SELECT @V_CDPRECOBASE = MAX(CDPRECOBASE)
      FROM PRECOBASECLI
      WHERE CDCLIENTE = @P_CDCLIENTE
        AND IDPRBASEPRIN = 'S';
   END
   ELSE BEGIN
      SELECT @V_CTREGISTRO = COUNT(CDPRECOBASE)
      FROM VENDEDOR
      WHERE 
         CDVENDEDOR = @P_CDVENDEDOR;

      IF @V_CTREGISTRO > 0 BEGIN
         SELECT @V_CDPRECOBASE = MAX(CDPRECOBASE)
         FROM VENDEDOR
         WHERE 
            CDVENDEDOR = @P_CDVENDEDOR;
      END
      ELSE BEGIN
         SELECT @V_CTREGISTRO = COUNT(CDPRECOBASE)
         FROM PRECOUTI
         WHERE CDFILIAL  = @P_CDFILIAL
           AND CDMODPGTO = @P_CDMODPGTO;

         IF @V_CTREGISTRO > 0 BEGIN
            SELECT @V_CDPRECOBASE = MAX(CDPRECOBASE)
            FROM PRECOUTI
            WHERE CDFILIAL  = @P_CDFILIAL
              AND CDMODPGTO = @P_CDMODPGTO;
         END; 
      END;
   END;
   RETURN(@V_CDPRECOBASE);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'BUSCA_PRECOBASE','4.05.131';
GO

