IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_update_branchinfo]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_update_branchinfo]
GO
CREATE procedure [dbo].[mps_update_branchinfo]
-- Add the parameters for the stored procedure here
@cmpid int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @id int = 0
    DECLARE @level int = 0
    DECLARE @fulltime nvarchar(100) = ''
    DECLARE @display nvarchar(100) = ''
    DECLARE @length int = 0
    DECLARE @space varchar(20) = '&emsp;'
    DECLARE @i int = 0
    
DECLARE @tem_branch table(id int IDENTITY(0,1),tem_id int,tem_level int,tem_company nvarchar(100),tem_fulltime nvarchar(100),tem_display nvarchar(100),PRIMARY KEY(id))
INSERT INTO @tem_branch SELECT bc_id,bc_level,bc_company,bc_fullname,bc_display FROM mps_branch WHERE  bc_cmpid = @cmpid ORDER BY bc_order, bc_level
SELECT @length=COUNT(tem_id) FROM @tem_branch

DECLARE @t_level int
DECLARE @t_company nvarchar(100)

WHILE @i < @length
BEGIN
SELECT @t_level=tem_level,@t_company=tem_company FROM @tem_branch WHERE id=@i
IF @t_level = @level
BEGIN
SET @level = @t_level
SET @display = LTRIM(RTRIM(@t_company))
IF @t_level = 0
BEGIN
SET @fulltime = @t_company
END ELSE
BEGIN
SET @fulltime = SUBSTRING(@fulltime,1,LEN(@fulltime)-CHARINDEX('/',REVERSE(RTRIM(@fulltime)))) + '/' + @t_company
END
END ELSE IF @t_level > @level
BEGIN
SET @level = @t_level
SET @display = LTRIM(RTRIM(@t_company))
SET @fulltime = @fulltime + '/' + @t_company
END ELSE
BEGIN
SET @level = @t_level
SET @display = LTRIM(RTRIM(@t_company))
SELECT TOP 1 @fulltime=tem_fulltime FROM @tem_branch WHERE id<@i AND tem_level=@level ORDER BY id DESC
IF @level = 0
BEGIN
SET @fulltime = @t_company
END ELSE
BEGIN
SET @fulltime = SUBSTRING(@fulltime,1,LEN(@fulltime)-CHARINDEX('/',REVERSE(RTRIM(@fulltime)))) + '/' + @t_company
END
END
WHILE @t_level > 0
BEGIN
SET @display = @space + @display
SET @t_level = @t_level - 1
END
UPDATE @tem_branch SET tem_display=@display,tem_fulltime=@fulltime WHERE id=@i
SET @i = @i + 1
END
UPDATE mps_branch SET bc_display=tem_display,bc_fullname=tem_fulltime FROM mps_branch,@tem_branch WHERE bc_id=tem_id
END