IF OBJECT_ID('UFD_BUSCA_CONTA_FILIAIS') IS NOT NULL
	BEGIN
		DROP FUNCTION UFD_BUSCA_CONTA_FILIAIS
	END
	
GO	

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE   FUNCTION [dbo].[UFD_BUSCA_CONTA_FILIAIS]	(	@CD_EMP 		INT,
														@CD_FILIAL 		INT,
														@TP_CONTA		INT)
RETURNS @RS_RETURN TABLE(
		CD_CTB_CNT_RED	 VARCHAR(100), 
		CD_CTB_CNT		 VARCHAR(50), 
		CNT_CENTRO_CTB	 INT,
		DS_CENTRO_CTB	 VARCHAR(100))

	BEGIN
		
		INSERT INTO @RS_RETURN
			SELECT 
				ISNULL(PRC_FILIAL_CNT_CTB.CD_CTB_CNT,'') AS CD_CTB_CNT, 
				ISNULL(PRC_FILIAL_CNT_CTB.CD_CTB_CNT_RED,0) AS CD_CTB_CNT_RED, 
				ISNULL(CTB_CENTRO_CUSTO.CNT_CENTRO_CTB,0) AS CNT_CENTRO_CTB, 
				ISNULL(CTB_CENTRO_CUSTO.DS_CENTRO_CTB,'') AS DS_CENTRO_CTB
				
			FROM PRC_FILIAL_CNT_CTB LEFT OUTER JOIN CTB_CENTRO_CUSTO ON
				PRC_FILIAL_CNT_CTB.CD_EMP = CTB_CENTRO_CUSTO.CD_EMP AND
				PRC_FILIAL_CNT_CTB.CD_CENTRO_CTB = CTB_CENTRO_CUSTO.CD_CENTRO_CTB
			
			WHERE PRC_FILIAL_CNT_CTB.CD_EMP = @CD_EMP
				AND PRC_FILIAL_CNT_CTB.CD_FILIAL = @CD_FILIAL
				AND PRC_FILIAL_CNT_CTB.TP_CNT_CTB = @TP_CONTA		
				  
		RETURN
		
	END
	
GO

