IF EXISTS(SELECT *
          FROM SYSOBJECTS O, SYSUSERS U
          WHERE O.NAME = 'MAIOR_ALIQUOTA'  AND
                TYPE   = 'FN'              AND
                U.UID  = O.UID             AND
                U.NAME = USER)
DROP FUNCTION MAIOR_ALIQUOTA
GO
CREATE FUNCTION MAIOR_ALIQUOTA (@P_CDFILIAL     VARCHAR(4),
                                @P_NRLANCTONF   VARCHAR(10)) RETURNS SMALLINT
AS
BEGIN
   DECLARE @V_VRALIQITEM  SMALLINT;
   DECLARE @V_NRSEQITPROD VARCHAR(04);
   DECLARE @V_CUR_NRSEQITPROD VARCHAR(04);
   DECLARE @V_CUR_VRALIQITEM  SMALLINT;
   SET @V_VRALIQITEM  = -1;
   SET @V_NRSEQITPROD = '0000';
   DECLARE C_CURSOR CURSOR FOR
      SELECT II.NRSEQITPROD, II.VRALIQITEM
        FROM ITEMPROIMPOS II , IMPOSTO I
       WHERE II.CDFILIAL   = @P_CDFILIAL
         AND II.NRLANCTONF = @P_NRLANCTONF
         AND II.CDIMPOSTO  = I.CDIMPOSTO
         AND I.CDIMPOSTONFE IN ('31', '35', '36')
   OPEN C_CURSOR;
   FETCH NEXT FROM C_CURSOR INTO @V_CUR_NRSEQITPROD, @V_CUR_VRALIQITEM;
   WHILE(@@FETCH_STATUS = 0) BEGIN
      IF @V_CUR_VRALIQITEM > @V_VRALIQITEM BEGIN
         SET @V_VRALIQITEM  = @V_CUR_VRALIQITEM;
         SET @V_NRSEQITPROD = @V_CUR_NRSEQITPROD;
      END;
      FETCH NEXT FROM C_CURSOR INTO @V_CUR_NRSEQITPROD, @V_CUR_VRALIQITEM;
   END;
   RETURN @V_NRSEQITPROD;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'MAIOR_ALIQUOTA','5.60.xxx';
GO