IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'CUSTO_PROD_LISTADESATU' AND
                 TYPE = 'FN' 		       AND
	              U.UID = O.UID            AND
	              U.NAME = USER)
DROP FUNCTION CUSTO_PROD_LISTADESATU
GO
CREATE FUNCTION CUSTO_PROD_LISTADESATU(
@P_CDFILIAL VARCHAR(4),
@P_CDPRODUTO VARCHAR(10),
@P_NRTIPOCUSTO INT,
@P_DTREFERENCIA DATETIME
) RETURNS VARCHAR(1)
AS
BEGIN
   DECLARE @V_IDPRECODESATU VARCHAR(1);
   DECLARE @V_CONTPRODESATU INT;

   IF (@P_NRTIPOCUSTO IN (6, 10, 44, 48, 30, 61, 31, 62)) BEGIN
      SELECT @V_CONTPRODESATU = COUNT(CUSTDESATU)
        FROM (SELECT 'N' AS CUSTDESATU
                FROM CUSTOSUP                 
               WHERE CUSTOSUP.CDFILIAL  = @P_CDFILIAL
                 AND CUSTOSUP.CDPRODUTO = @P_CDPRODUTO
                 AND @P_DTREFERENCIA BETWEEN CUSTOSUP.DTCUSTOSUP AND CUSTOSUP.DTFINCUSTSUP
               UNION ALL
              SELECT 'N' AS CUSTDESATU
                FROM FILIAL, PARASUPRI, PARAMPRODSUP, CUSTOSUP
               WHERE FILIAL.CDFILIAL = @P_CDFILIAL
                 AND PARASUPRI.CDFILIAL = ISNULL(FILIAL.CDFILCENTCMP, FILIAL.CDFILIAL)
                 AND ISNULL(PARASUPRI.IDUTILCONSSOLIOL, 'N') = 'S'
                 AND PARAMPRODSUP.CDFILIAL = @P_CDFILIAL
                 AND PARAMPRODSUP.CDPRODUTO = @P_CDPRODUTO
                 AND CUSTOSUP.CDFILIAL = PARAMPRODSUP.CDFILIOPELOG
                 AND CUSTOSUP.CDPRODUTO = @P_CDPRODUTO
                 AND @P_DTREFERENCIA BETWEEN CUSTOSUP.DTCUSTOSUP AND CUSTOSUP.DTFINCUSTSUP) AS PRECODESATU;
      IF (@V_CONTPRODESATU = 0) BEGIN
         SET @V_IDPRECODESATU = 'S';
      END
      ELSE BEGIN
         SET @V_IDPRECODESATU = 'N';
      END;
   END
   ELSE BEGIN
      SET @V_IDPRECODESATU = 'N';
   END;
   RETURN(@V_IDPRECODESATU);
END
GO
-- VERSAO --
EXEC ATUVEROBJ 'CUSTO_PROD_LISTADESATU','5.07.005';
GO