没有测试,没有考虑效率:craete function f_AccounName(@account_no varchar(200))
returns varchar(2000)
as
begin
    declare @t varchar(2000)
    declare @PARENT_ACCOUNT   varchar(200)
    set @t=''
    set @PARENT_ACCOUNT=''
    select @t=ACCOUNT_NAME,@PARENT_ACCOUNT=PARENT_ACCOUNT from a 
    where @account_no=account_no
    if @PARENT_ACCOUNT='' or @PARENT_ACCOUNT is null
    set @t=dbo.f_AccounName(@PARENT_ACCOUNT)+'/'+@t
    return @t
 
end
go

解决方案 »

  1.   

    CREATE function f_AccountName(
    @account_no  varchar(32)
    )
    returns varchar(400)
    as
    begin
      declare @is_no varchar(32)
      declare @s  varchar(400)
      set @is_no = @account_no
      set @s=''
      while isnull((select LAYER_LEVEL from a where account_no = @is_no),1) > 1  
      --while (select parent_account from a where account_no=@is_no)<>'' or (select parent_account from a where account_no=@is_no) is not null
      begin
       select @is_no = parent_account ,@s=@s+account_name from a where account_no = @is_no
       set @s=@s+'/'
      end
      if (select layer_level from a where account_no=@is_no)=1
        select  @s=@s+account_name from a  where account_no=@is_no
      return(@s)
    end
    可得到的结果有差异:
    select account_no,f_AccountName(account_no) as name from a
    account_no   name
    1001         现金           
    1002         银行存款        
    100201       工行存款/银行存款        
    100202       农行存款/银行存款       
    2171         应交税金         
    217101       应交增值税/应交税金
    21710102     已交税金/应交增值税/应交税金
    ........
      

  2.   

    次序反了嘛begin
       select @is_no = parent_account ,@s=@s+account_name from a where account_no = @is_no
       set @s=@s+'/'
    end--〉begin
       select @is_no = parent_account ,@s=account_name+'/'+@s from a where account_no = @is_no
    end
      

  3.   

    一时忙晕了,谢谢“CSDMN冒牌经理 V0.3”的提醒
    我马上结贴。