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

CREATE FUNCTION dbo.CF_Seg_Menu_Leer_Grupo (@pId_Modulo INT, @pId_Menu INT)
RETURNS INT
AS
BEGIN
DECLARE @Id_Menu_Padre INT 

SELECT @Id_Menu_Padre = ME.Id_Menu_Padre
			FROM 	dbo.Seg_Menu_Mod ME
			WHERE ME.Id_Menu = @pId_Menu 
			AND ME.Id_Modulo = @pId_Modulo

IF ISNULL(@Id_Menu_Padre,0) = 0 
	SET @Id_Menu_Padre = @pId_Menu 
ELSE
	SET @Id_Menu_Padre = dbo.CF_Seg_Menu_Leer_Grupo(@pId_Modulo,@Id_Menu_Padre) 

RETURN @Id_Menu_Padre
END

/*
SELECT dbo.CF_Seg_Menu_Leer_Grupo(1,130)
SELECT dbo.CF_Seg_Menu_Leer_Grupo(1,439)
SELECT dbo.CF_Seg_Menu_Leer_Grupo(1,276)

*/