
DECLARE @VALOR INT = 99;

IF EXISTS (SELECT * 
			 FROM PRC_EMP_CONFIG 
			WHERE CD_CHAVE = 'FLAG_DEVO_COMPRA_POR_DIVISAO'  
			  AND DT_ULT_ALT < '20200417' )

BEGIN 			 
	SET @VALOR = (SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'FLAG_DEVO_COMPRA_POR_DIVISAO' ) 

	IF @VALOR IS NULL 
	BEGIN 
		UPDATE PRC_EMP_CONFIG 
		   SET VALOR = 0,
			   DT_ULT_ALT = '20200417'
		 WHERE CD_CHAVE = 'FLAG_DEVO_COMPRA_POR_DIVISAO' 
		   AND VALOR IS NULL 
	END
	ELSE
	BEGIN 
		IF @VALOR = 0
		BEGIN
			UPDATE PRC_EMP_CONFIG 
			   SET VALOR = 1,
				   DT_ULT_ALT = '20200417'
			 WHERE CD_CHAVE = 'FLAG_DEVO_COMPRA_POR_DIVISAO' 
			   AND VALOR    = 0
			   AND DT_ULT_ALT < '20200417'
		END 
		ELSE 
		BEGIN 
			IF @VALOR = 1 
			BEGIN
				UPDATE PRC_EMP_CONFIG 
				   SET VALOR = 0,
					   DT_ULT_ALT = '20200417'
				 WHERE CD_CHAVE = 'FLAG_DEVO_COMPRA_POR_DIVISAO' 
				   AND VALOR  = 1
				   AND DT_ULT_ALT < '20200417'
			END 
		END 

	END	
END  
  