IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_update_extresinfo]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_update_extresinfo]
GO

-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[mps_update_extresinfo]
-- Add the parameters for the stored procedure here
@cmpid int,
@mytag int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
DECLARE @id int = 0
    DECLARE @level int = 0
    DECLARE @father int = 0
    DECLARE @full nvarchar(100) = ''
    DECLARE @length int = 0
    DECLARE @i int = 0
    
DECLARE @tem_ext_resource table(id int IDENTITY(0,1),tem_id int,tem_level int,tem_father int,tem_type nvarchar(100),tem_full nvarchar(100),PRIMARY KEY(id))
INSERT INTO @tem_ext_resource SELECT etc_id,etc_level,etc_father,etc_type,etc_full FROM mps_ext_resource WHERE etc_cmpid = @cmpid AND etc_tag = @mytag ORDER BY etc_order, etc_level
SELECT @length=COUNT(tem_id) FROM @tem_ext_resource

DECLARE @t_id int
DECLARE @t_level int
DECLARE @t_type nvarchar(100)

WHILE @i < @length
BEGIN
SELECT @t_id=tem_id,@t_level=tem_level,@t_type=tem_type FROM @tem_ext_resource WHERE id=@i
IF @t_level = @level
BEGIN
SET @id = @t_id
SET @level = @t_level
IF @t_level = 0
BEGIN
SET @full = @t_type
END ELSE
BEGIN
SET @full = SUBSTRING(@full,1,LEN(@full)-CHARINDEX('/',REVERSE(RTRIM(@full)))) + '/' + @t_type
END
END ELSE IF @t_level > @level
BEGIN
SET @father = @id
SET @id = @t_id
SET @level = @t_level
SET @full = @full + '/' + @t_type
END ELSE
BEGIN
SET @level = @t_level
SELECT TOP 1 @father=tem_father,@full=tem_full FROM @tem_ext_resource WHERE id<@i AND tem_level=@level ORDER BY id DESC
SET @id = @t_id
IF @level = 0
BEGIN
SET @full = @t_type
END ELSE
BEGIN
SET @full = SUBSTRING(@full,1,LEN(@full)-CHARINDEX('/',REVERSE(RTRIM(@full)))) + '/' + @t_type
END
END
WHILE @t_level > 0
BEGIN
SET @t_level = @t_level - 1
END
UPDATE @tem_ext_resource SET tem_father=@father,tem_full=@full WHERE id=@i
SET @i = @i + 1
END
UPDATE mps_ext_resource SET etc_full=tem_full,etc_father=tem_father FROM mps_ext_resource,@tem_ext_resource WHERE etc_id=tem_id
END