SET NOCOUNT ON

DECLARE @STR_EXEC VARCHAR(2000)

SET @STR_EXEC = 'CREATE '

--FN = Scalar function
--FS = Assembly (CLR) scalar-function
--FT = Assembly (CLR) table-valued function
--TF = Table function

IF EXISTS(
	SELECT 
		ID 
	FROM 
		SYSOBJECTS 
	WHERE 
		NAME = 'UFD_PRC_FILIAL_CONFIG' AND XTYPE in ('FN', 'FS', 'FT', 'TF'))
BEGIN
	SET	@STR_EXEC = 'ALTER '
END

	SET @STR_EXEC = @STR_EXEC + 'FUNCTION [DBO].[UFD_PRC_FILIAL_CONFIG](@CD_EMP INT, @CD_FILIAL INT, @CD_CHAVE VARCHAR(255), @DEFAULT_RETURN VARCHAR(255)) RETURNS VARCHAR
			AS
			BEGIN
				DECLARE @RETURN VARCHAR(255)
	
				SET @RETURN = COALESCE((SELECT COALESCE(VALOR,@DEFAULT_RETURN)  FROM PRC_FILIAL_CONFIG WHERE CD_EMP = @CD_EMP AND CD_FILIAL = @CD_FILIAL AND CD_CHAVE = @CD_CHAVE), @DEFAULT_RETURN)
	
				RETURN @RETURN
  			END'	
		
	EXEC (@STR_EXEC)