IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CP_Seg_Menu_Mod_Ordenar') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE dbo.CP_Seg_Menu_Mod_Ordenar
END
GO

CREATE PROCEDURE dbo.CP_Seg_Menu_Mod_Ordenar @Id_Modulo INT, @Id_Menu_Padre INT
AS
BEGIN
SET NOCOUNT ON

SET @Id_Menu_Padre = dbo.CF_Seg_Menu_Leer_Grupo(@Id_Modulo , @Id_Menu_Padre )

SELECT ME.*
	INTO #z_Seg_Menu_Mod
			FROM 	dbo.Seg_Menu D, 
					dbo.Seg_Menu_Mod ME, 
					dbo.Seg_Menu P 
			WHERE 
			D.Id_Menu = ME.Id_Menu 
			AND ME.Id_Menu_Padre = P.Id_Menu 
			AND ME.Id_Modulo = @Id_Modulo
			AND (ME.Id_Menu_Padre = @Id_Menu_Padre
			OR ME.Id_Menu_Padre IN (SELECT Id_Menu FROM dbo.Seg_Menu_Mod WHERE Id_Menu_padre=@Id_Menu_Padre))
			AND D.Id_Menu <> 0 
			ORDER BY ME.Orden



ALTER TABLE #z_Seg_Menu_Mod ADD _Orden INT IDENTITY(100,10)


UPDATE Seg_Menu_Mod SET Orden = S2._Orden FROM Seg_Menu_Mod S1,#z_Seg_Menu_Mod S2
	WHERE S1.Id_Menu = S2.Id_Menu AND S1.Id_Modulo = S2.Id_Modulo
DROP TABLE #z_Seg_Menu_Mod

END

/*
exec [CP_Seg_Menu_Mod_Ordenar] 1,39

*/