IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE
              O.NAME = 'LOCALESTOQUE_PADRAO' AND
              TYPE = 'P' 			              AND
              U.UID = O.UID             		  AND
              U.NAME = USER)

DROP PROCEDURE LOCALESTOQUE_PADRAO
GO

CREATE PROCEDURE LOCALESTOQUE_PADRAO
                 @P_CDFILIAL  VARCHAR(04),
                 @P_CDPRODUTO VARCHAR(10),
                 @P_CDALMOXARIFE VARCHAR(06) OUTPUT,
                 @P_CDLOCALESTOQ VARCHAR(06) OUTPUT

AS

   DECLARE @V_IDUTILALMOX  VARCHAR(01);
   DECLARE @V_IDUTILLCESTQ VARCHAR(01);
   DECLARE @V_CDALMOXARIFE VARCHAR(06);
   DECLARE @V_CDLOCALESTOQ VARCHAR(06);
   DECLARE @V_CDPRODESTO   VARCHAR(10);
   DECLARE @V_COUNT        NUMERIC;

BEGIN

   SELECT @V_IDUTILALMOX = ISNULL(MAX(IDUTILALMOX),'N'),
          @V_IDUTILLCESTQ = ISNULL(MAX(IDUTILLCESTQ),'N')
   FROM PARAMFILIAL
   WHERE CDFILIAL = @P_CDFILIAL;

   SELECT @V_CDPRODESTO = CDPRODESTO
   FROM PRODUTO
   WHERE CDPRODUTO = @P_CDPRODUTO;

   IF @V_IDUTILALMOX = 'N' BEGIN
      SET @V_CDALMOXARIFE = ' ';

      SELECT @V_COUNT = COUNT(*)
      FROM ALMOXARIFADO
      WHERE CDFILIAL = @P_CDFILIAL;

      IF @V_COUNT = 0 BEGIN
         INSERT INTO ALMOXARIFADO
         (CDFILIAL, CDALMOXARIFE, DSALMOXARIFE)
         VALUES
         (@P_CDFILIAL, ' ', ' ');
      END;
   END
   ELSE BEGIN
      SELECT @V_CDALMOXARIFE = MAX(CDALMOXARIFE)
      FROM PRODFILI
      WHERE CDFILIAL  = @P_CDFILIAL AND
            CDPRODUTO = @V_CDPRODESTO;

      IF (@V_CDALMOXARIFE IS NULL OR @V_CDALMOXARIFE = ' ') BEGIN
         SELECT @V_CDALMOXARIFE = MAX(CDALMOXARIFE)
         FROM PARAMFILIAL
         WHERE CDFILIAL  = @P_CDFILIAL;
      END;
   END;

   IF @V_IDUTILLCESTQ = 'N' BEGIN
      SET @V_CDLOCALESTOQ = ' ';

      SELECT @V_COUNT = COUNT(*)
      FROM LOCALESTOQUE
      WHERE CDFILIAL     = @P_CDFILIAL AND
            CDALMOXARIFE = ' ';

      IF @V_COUNT = 0 BEGIN
         INSERT INTO LOCALESTOQUE
         (CDFILIAL, CDALMOXARIFE, CDLOCALESTOQ, DSLOCALESTOQ)
         VALUES
         (@P_CDFILIAL, ' ', ' ', ' ');
      END;
   END
   ELSE BEGIN
      SELECT @V_CDLOCALESTOQ = MAX(CDLOCALESTOQ)
      FROM PRODFILI
      WHERE CDFILIAL  = @P_CDFILIAL AND
            CDPRODUTO = @V_CDPRODESTO;

      IF (@V_CDLOCALESTOQ IS NULL OR @V_CDLOCALESTOQ = ' ')BEGIN
         SELECT @V_CDLOCALESTOQ = MAX(CDLOCALESTOQ)
         FROM PARAMFILIAL
         WHERE CDFILIAL  = @P_CDFILIAL;
      END;
   END;

   SET @P_CDALMOXARIFE = @V_CDALMOXARIFE;
   SET @P_CDLOCALESTOQ = @V_CDLOCALESTOQ;
END;
GO