IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_update_account_item]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_update_account_item]
GO
create proc [dbo].[mps_update_account_item]
 @ai_id bigint,
 @ai_caption nvarchar(200),
 @ai_code varchar(100),
 @oldname nvarchar(200),
 @faiid bigint
 as 
 begin
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

UPDATE mps_account_item SET 
ai_caption =  CASE WHEN @ai_caption = '_none_' THEN ai_caption ELSE @ai_caption END,
ai_code =  CASE WHEN @ai_code = '_none_' THEN ai_code ELSE @ai_code END,
ai_display = case when @ai_caption = '_none_' then ai_display else REPLACE(ai_display, @oldname, @ai_caption) end,
ai_full = case when @ai_caption = '_none_' then ai_full 
else SUBSTRING(ai_full,0,len(ai_full)-(charindex('/',reverse(ai_full))-2))+@ai_caption end
where ai_id = @ai_id

declare @s int;
select @s = CHARINDEX('/' ,ai_full) from mps_account_item where ai_id = @ai_id
if @s=0 and @ai_caption != '_none_'
begin
UPDATE mps_account_item SET ai_full = @ai_caption where ai_id = @ai_id;
end
if @ai_caption !='_none_'
begin
--递归更新
WITH cte AS (
select ai_id,ai_caption,ai_faiid ,CAST(ai_full AS VARCHAR(100)) AS fullname
from mps_account_item
WHERE ai_faiid = @faiid and ai_id=@ai_id
UNION ALL 
SELECT a.ai_id,a.ai_caption,a.ai_faiid ,CAST(b.fullname+'/'+a.ai_caption AS VARCHAR(100)) AS FULLname
FROM mps_account_item a INNER JOIN cte b ON a.ai_faiid=b.ai_id)

UPDATE a  SET a.ai_full = b.fullname FROM mps_account_item a right JOIN (SELECT * FROM cte) as b ON a.ai_id = b.ai_id;
end

set nocount off
 end