IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'[dbo].[CF_SCA_IdControlador]') 
                   and [type] = 'FN')
BEGIN
    DROP FUNCTION dbo.CF_SCA_IdControlador
END
GO

CREATE FUNCTION [dbo].[CF_SCA_IdControlador](@pNro_Serie VARCHAR(30), @pIPServidor VARCHAR(15))
RETURNS SMALLINT
AS
BEGIN
DECLARE @Id_Controlador		SMALLINT
DECLARE @IPServerFormateada	VARCHAR(15)

SET @IPServerFormateada = (dbo.CF_SCA_FormatoIP(@pIPServidor))

SET @Id_Controlador =	(SELECT MAX(ISNULL(CC.Id_Controlador, 0)) 
						FROM Cd_Controladores CC, CD_Accesos CA, CD_Servers CS
						WHERE 
						CC.Id_Acceso = CA.Id_Acceso
						AND CA.Pc_Server = CS.Pc_Server
						AND dbo.CF_SCA_FormatoIP(CS.Ip) = @IPServerFormateada
						AND CC.Nro_Serie = @pNro_Serie)					

RETURN ISNULL(@Id_Controlador, 0)

END